首页 > 解决方案 > 笑话模拟函数返回未定义而不是对象

问题描述

我正在尝试在 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() 但它也不起作用。

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

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

标签: javascriptnode.jsmockingjestjsjwt

解决方案


解决此问题的一种方法是模拟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' })
});

推荐阅读