gpt4 book ai didi

javascript - 如何将 res 对象传递到 Jest 模拟函数中的回调函数中?

转载 作者:行者123 更新时间:2023-12-01 01:03:45 25 4
gpt4 key购买 nike

我正在用nodejs开发一个网络服务器,目前正在尝试通过 Jest 测试覆盖所有分支。我有一个函数 logout,它从express 中获取 req 和 res 对象。我需要在 if 语句中进行开 Jest 测试。

// 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);

});

最佳答案

test()app.test.js 中,您将 res 参数作为 null 传递。您会收到错误TypeError: Cannot read property 'sendStatus' of null,这通常是因为您传递了null。该回调是正确的,但调用错误。尝试像传递 req 一样传递 res

请务必阅读以下内容:回调函数MDN(理论):https://developer.mozilla.org/en-US/docs/Glossary/Callback_function

回调函数(FelDev on Medium - 实践和理论):https://medium.com/javascript-in-plain-english/callbacks-in-node-js-how-why-when-ac293f0403ca

你好,李子!

关于javascript - 如何将 res 对象传递到 Jest 模拟函数中的回调函数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55820217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com