javascript - 笑话模拟函数返回未定义而不是对象
问题描述
我正在尝试在 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() 但它也不起作用。
我知道这里有一些关于堆栈溢出的类似线程,但不幸的是,所提出的解决方案都不适合我。
如果需要更多上下文,这是我的完整测试套件。提前致谢。
解决方案
解决此问题的一种方法是模拟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' })
});
推荐阅读
- android - 比较android sqlite数据库中的日期
- spring-boot - 如何为来自 RestTemplate 1 的基于 Rest 模板 2 的响应编写 Mockito
- bash - 如何验证我的 bash 脚本以显示在提示用户或使用 echo 语句出错时只能输入 2 个文件名
- html - Heroku 视图有问题
- mongodb - mongodb社区服务器是否支持两阶段提交?
- c# - 带有多个参数的 C# Launch 应用程序似乎不适用于文本框
- c# - 如何使用字符串变量c#中的给定路径获取JSON对象
- mysql - 添加并返回当前日期 NodeJs
- java - 扫描发现在 android 应用程序中不起作用
- oracle - 完全下载 APEX 站点