简体   繁体   English

开玩笑模拟 function 返回未定义而不是 object

[英]Jest mock function returns undefined instead of object

I'm trying to create unit tests for my auth middleware in an Express app.我正在尝试在 Express 应用程序中为我的身份验证中间件创建单元测试。

The middleware is as simple as this:中间件就这么简单:

const jwt = require('jsonwebtoken');

const auth = (req, res, next) => {
    const tokenHeader = req.headers.auth; 

    if (!tokenHeader) {
        return res.status(401).send({ error: 'No token provided.' });
    }

    try {
        const decoded = jwt.verify(tokenHeader, process.env.JWT_SECRET);

        if (decoded.id !== req.params.userId) {
            return res.status(403).json({ error: 'Token belongs to another user.' });
        }

        return next();
    } catch (err) {
        return res.status(401).json({ error: 'Invalid token.' });
    }
}

module.exports = auth; 

And this is my test, where I want to ensure that if the token is ok everything will go smoothly and the middleware just calls next() :这是我的测试,我想确保如果令牌没问题,一切都会顺利 go 并且中间件只调用next()

it('should call next when everything is ok', async () => {
        req.headers.auth = 'rgfh4hs6hfh54sg46';
        jest.mock('jsonwebtoken/verify', () => {
            return jest.fn(() => ({ id: 'rgfh4hs6hfh54sg46' }));
        });
        await auth(req, res, next);
        expect(next).toBeCalled();
});

But instead of returning the object with and id field as desired, the mock always returns undefined.但不是根据需要返回 object 和 id 字段,而是模拟总是返回未定义。 I have tried returning the object instead of jest.fn() but it didn't work too.我尝试返回 object 而不是 jest.fn() 但它也没有用。

I know there are some similar threads here on stack overflow but unfortunately none of the solutions proposed worked for me.我知道这里有一些关于堆栈溢出的类似线程,但不幸的是,所提出的解决方案都不适合我。

If more context is needed, here is my full test suite.如果需要更多上下文,是我的完整测试套件。 Thanks in advance.提前致谢。

One way to solve this is to mock the jsonwebtoken module and then use mockReturnValue on the method to be mocked.解决此问题的一种方法是模拟jsonwebtoken模块,然后在要模拟的方法上使用mockReturnValue Consider this example:考虑这个例子:

const jwt = require('jsonwebtoken');

jest.mock('jsonwebtoken');

jwt.verify.mockReturnValue({ id: 'rgfh4hs6hfh54sg46' });

it('should correctly mock jwt.verify', () => {
  expect(jwt.verify("some","token")).toStrictEqual({ id: 'rgfh4hs6hfh54sg46' })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM