【问题标题】:Jest mock function returns undefined instead of object笑话模拟函数返回未定义而不是对象
【发布时间】:2020-08-05 22:35:42
【问题描述】:

我正在尝试在 Express 应用中为我的身份验证中间件创建单元测试。

中间件就这么简单:

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; 

这是我的测试,我想确保如果令牌没问题,一切都会顺利进行,并且中间件只是调用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();
});

但不是根据需要返回带有 id 字段的对象,mock 总是返回 undefined。我已经尝试返回对象而不是 jest.fn() 但它也不起作用。

我知道这里有一些类似的堆栈溢出线程,但不幸的是,所提出的解决方案都不适合我。

如果需要更多上下文,here 是我的完整测试套件。提前致谢。

【问题讨论】:

    标签: javascript node.js mocking jestjs jwt


    【解决方案1】:

    解决这个问题的一种方法是模拟jsonwebtoken 模块,然后在要模拟的方法上使用mockReturnValue。考虑这个例子:

    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' })
    });
    

    【讨论】:

      猜你喜欢
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多