【问题标题】:How do you pass the res object into the callback function in a jest mock function?你如何将 res 对象传递给 jest mock 函数中的回调函数?
【发布时间】: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


    【解决方案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

    你好,李子!

    【讨论】:

    • 谢谢,是的,事实证明我只是错过了将 res 作为 null 传递。一旦我将 null 更改为 res 它就修复了它。谢谢!
    【解决方案2】:

    最简单的回调示例如下所示:link Yu 可以轻松传递一些道具 :)

    【讨论】:

    • 链接可能会在一段时间后过期,请尝试在您的答案中添加代码。
    猜你喜欢
    • 1970-01-01
    • 2016-09-03
    • 2016-02-12
    • 1970-01-01
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多