【发布时间】: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