类型错误模拟快速响应对象



我目前正在尝试使用sinonsinon-express-mock编写测试来模拟不正确的请求,然后在我的应用程序中调用验证函数,确保验证函数返回正确的响应状态 (400)。但是,目前我收到错误TypeError: Cannot read property 'send' of undefined.我以为send会和res对象的其余部分一起被嘲笑,但如果不是,我怎么能做到这一点呢?提前谢谢。

我正在测试的功能:

export const validateItemRequest = (req, res) => {
if (!req.query.number) {
return res.status(400).send('Number not specified');
} else if ( req.query.number % 1 !== 0) {
return res.status(400).send('Incorrect number syntax');
} 
};

测试代码:

describe('item', function() {
it('should only accept valid requests', function() {
const itemRequest = {
query: {
number: 'abcde',
},
};
const req = mockReq(request);
const res = mockRes();
itemController.validateItemRequest(req, res);
});
});

sinon-express-mock目前不支持链接。添加链接支持存在一个未解决的问题,但这些方法当前不返回对象,因此无法从res.status链接到send

我只需要一些响应方法进行测试,所以我做了我自己的响应间谍,如下所示:

var response = {  
status: sinon.spy(function() { return response; }),  
send: sinon.spy(),  
sendStatus: sinon.spy(),
reset: function() {
for (var method in this) {
if (method !== 'reset') {
this[method].reset();
}
}
}
};

请注意,我只返回来自status的响应,因为您不应该将sendsendStatus联系起来。

response = { 
json:(obj) => { response.body = obj },
status:function(status) {
response.statusValue = status;
return this;
}

最新更新