Jest mock函数返回undefined而不是对象。

问题描述 投票:0回答:1

我试图为我在Express应用中的auth中间件创建单元测试。

中间件就像这样简单。

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

但是mock并没有如愿返回带有id字段的对象,而是总是返回undefined。我试过用jest.fn()来代替返回对象,但也没有用。

我知道在堆栈溢出上有一些类似的帖子,但不幸的是,所提出的解决方案对我来说都不奏效。

如果需要更多的背景。此处 是我的完整测试套件。先谢谢你。

javascript node.js mocking jwt jest
1个回答
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' })
});
© www.soinside.com 2019 - 2024. All rights reserved.