[英]How to send response using jest function? It gives async callback error
我尝试使用玩笑来模拟模型响应。 它将进入我的jest.mock.createMondayBox函数中,并且可以显示“ hello world”,这意味着它可以真正进入替换原始模型的模拟模型中。
车型/ mondayModel.js
var mondayModel = function() {
function createBox (req, payload, callback) {
...
boxClient.request(req, {
method: 'POST'
path:
body:
headers: { }
}, function(error, response) {
if(error || (response.statusCode && response.statusCode !== 200)) {
return callback(new ErrorObject({
errorName:'createBoxFailure',
errorMessage: 'Error in creating box'
})
}
return callback(null, {resultSet: response.body})
})
}
function fnB (req, callback) { }
function fnC (req, callback) { }
function fnD (req, callback) { }
return {
createBox: createBox,
fnB: fnB,
fnC: fnC,
fnD: fnD
}
}
module.exports = mondayModel
控制器/ boxController.js
var MondayModel = require('../models/mondayModel');
function createMondayBox(req, res, next) {
...
var mondayModel = new MondayModel();
mondayModel.createBox(req, payload, function(error, result) {
if(error) {
res.json({'status': 'BADREQUEST', 'statusCode': 400})
} else {
var mondaybox = result.resultSet.mondayboxes && result.resultSet.mondayboxes[0]
var mappedResponse = Response.mapCreateMondaybox(req, resultSet);
utils.logKK(req, utils.getKK(mappedResponse.mondayboxes[0]))
res.json(mappedResponse);
}
...
}
}
boxController-test.jest
let boxController = null
describe('money tracker', () => {
beforeAll(() => {
jest.mock('../../../../models/mondayBox',
() => function mondayBoxModel() {
console.log("hello world")
return {
createBox: (req, payload, callback) => {
return callback(null, {
resultSet: {
mondayboxes: [{ name: '1' }, { name: '2' }]
},
json: jest.fn()
})}
fnB: jest.fn(),
fnC: jest.fn(),
fnD: jest.fn()
}
}
}))
)
boxController = require('../controllers/boxController')
})
test('success case', done => {
const req = {}
const res = new Promise(r =>
r({ json: jest.fn(), status: jest.fn() })
)
mondayBoxController.createMondayBox(req, res, (cbErr, cbRes) => {
expect(res.json).toBeCalled();
done()
})
}
}
TypeError:res.json不是函数
我可以知道如何解决这个问题吗? 如何编写模拟模型响应? 谢谢
首先,您只需要测试控制器,因此您应该
将控制器更新为
var MondayModel = require('../models/mondayModel');
function createMondayBox(req, res, next) {
...
var mondayModel = new MondayModel();
mondayModel.createBox(req, payload, function(error, result) {
if(error) {
res.json({'status': 'BADREQUEST', 'statusCode': 400})
} else {
var mondaybox = result.resultSet.mondayboxes &&
result.resultSet.mondayboxes[0]
var mappedResponse = Response.mapCreateMondaybox(req, resultSet);
utils.logKK(req, utils.getKK(mappedResponse.mondayboxes[0]))
res.json(mappedResponse);
next();
}
...
}
}
并在测试文件中:
import {createRequest, createResponse} from 'node-mocks-http'
import boxController from 'controller/boxController.js'
import mondayBoxModal from 'models/mondayBox';
jest.mock('models/mondayBox', () => () => ({ createBox: (req, payload, cb) => cb(null, { resultSet: { mondayboxes: ['resultsData']} } }));
describe('money tracker', () => {
let req;
let res;
let next = jest.fn;
beforeEach(() => {
jest.clearAllMocks();
req = createRequest({
method: 'GET',
url: '/user/42',
params: {
id: 42
}
});
res = httpMocks.createResponse();
res.json = jest.fn;
})
test('success case', done => {
const req = {}
mondayBoxController.createMondayBox(req, res, (cbErr, cbRes) => {
expect(res.json).toBeCalled();
done()
})
}
}
您的函数transfer(req, res, next)
接受3个参数,并在调用boxController.transfer(req, {}, fn)
传递空对象时使用res.json()
。 它可能在这里无声地失败了。
在您的样本中, transfer
根本没有调用。
请确保您的示例准确地类似于实际代码。
更新
它与异步无关
如果你写这个
const res = new Promise(r =>
r({ json: jest.fn(), status: jest.fn() })
)
mondayBoxController.createMondayBox(req, res, (cbErr, cbRes) => {
expect(res.json).toBeCalled();
done();
})
然后
mondayModel.createBox(req, payload, function (error, result) {
console.log(res); // Promise, which has no json method
console.log(res.json); // undefined
// but
console.log(await res); // the desired mocked res obj
// btw this is incorrect usage of await
if (error) {
res.json();
} else {
...
}
});
mondayModel.createBox
的回调中的res
就是您传递给mondayBoxController.createMondayBox(req, res, handler)
。
相反,这样做
const res = {
json: jest.fn(); // or whatever behaviour you desire
};
mondayBoxController.createMondayBox(req, res, handler);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.