我正在尝试在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和id字段的对象,而是总是返回未定义的。我尝试返回该对象而不是jest.fn(),但是它也不起作用。
我知道堆栈溢出有一些类似的线程,但是不幸的是,没有提出的解决方案对我有用。
如果需要更多上下文,here是我的完整测试套件。预先感谢。
答案 0 :(得分: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' })
});