我正在使用Express和Express-JWT。
在Express()实例中,我使用:
const api = express()
api.use(jwt({
// my options
}))
为了在测试中模拟这一点,我使用了一个包含以下内容的mocks\express-jwt\index.js
文件:
const jwt = jest.fn().mockImplementation(options => (req, res, next) => {
// set dummy req.user and call
next()
})
module exports = jwt
一切正常。 现在我想跳过根端点的JWT,因此我将jwt用法更改为:
api.use(jwt({
// my options
}).unless({path:['/']}))
在我的模拟文件中,我添加了:
jwt.unless = jest.fn().mockImplementation(options => (req, res, next) => {
next()
})
但是,现在测试总是以function unless is not defined
失败。
有人知道如何嘲笑这种unless
行为吗?
答案 0 :(得分:0)
unless
用作属性,原因是调用jwt
。
因此要对其进行模拟,请将unless
模拟作为您的jwt
模拟返回的函数的属性添加:
const jwt = jest.fn().mockImplementation(options => {
const func = (req, res, next) => {
// set dummy req.user and call
next();
};
func.unless = jest.fn().mockImplementation(options => (req, res, next) => {
next();
});
return func;
});
module.exports = jwt;
答案 1 :(得分:0)
Brian的建议答案对我不起作用,因为在func
方法中,我做了一些伪造授权检查的工作。
我的问题是我需要跳过unless
函数给定的方法和路径的授权检查。
我现在的解决方案是这样的:
const jet = jest.fn(options => {
let mockFunc = (req, res, next) => {
// get authorization from request
let token = ...
if (!token) {
res.status(401).send('No token provided')
} else {
req.token = token
next()
}
}
mockFunc.unless = jest.fn(args => (req, res, next) => {
if (args.method == req.method && arg.path == req.path) {
// not do authorization check for excluded endpoint via unless
next()
else {
mockFunc(req, res, next)
}
}
return mockFunc
}
感谢Brian为我指出正确的方向。