【发布时间】:2019-04-23 22:25:58
【问题描述】:
我正在 nodejs 中开发一个网络服务器,目前正在尝试通过开玩笑测试覆盖所有分支。我有一个功能,注销,它接收来自 express 的 req 和 res 对象。我需要在 if 语句中开玩笑测试。
// app.js
function logout(req, res) {
// console.log(req.session.destroy.toString());
req.session.destroy(function (err){
if (err){
console.error(err);
res.sendStatus(500);
}
console.log('Logged out');
res.redirect('/');
});
}
// app.test.js
let res = {sendStatus: jest.fn((inp) => inp)};
let req = {
session: { destroy: jest.fn((callback) => {
callback('TEST_ERROR');
})}
};
test('Test /logout error', async () => {
await logout(req, null);
expect(req.session.destroy.mock.calls.length).toEqual(1);
});
我已经搜索过类似的答案,我能找到的唯一有用的主题是this,它允许我进入 if 语句,但它现在抛出错误:TypeError: Cannot read property 'sendStatus' of null。
无论如何我可以允许回调函数访问我在 app.test.js 中定义的资源吗?非常感谢任何正确方向的帮助或指示。
已解决
正如 plumthedev 正确指出的那样,在我的 app.test.js 中,当我调用 loguout 时,我传递了我错过的 null。一旦我将其更改为 res,它就解决了我的问题。
// app.test.js
test('Test /logout error', async () => {
await logout(req, res);
expect(req.session.destroy.mock.calls.length).toEqual(1);
});
【问题讨论】:
标签: javascript node.js express callback jestjs