我有以下异步中间件,它使用多个 try-catch 来检查某些 http 调用的响应。我希望对这个中间件进行单元测试,但在模拟“下一个”回调时遇到了困难。当我这样包装它时:
it('should test for auth', () => {
logon(req, res, function() {
expect(res.locals).toBe(true)
})
})
它似乎并没有实际运行该函数并在之后运行 expect
。关于如何模拟 request
、response
和 next
对象以便测试最终值 (res.locals) 的任何想法?谢谢。
async function logon(req, res, next) {
if (!req.query.isAuth)
req.locals.auth = false;
next()
}
try {
const getData = await http.get(/logon);
if (getData.status == 200) {
res.locals.auth = true;
} else {
res.locals.auth = false;
try {
const secondCall = http.get(/logon2);
if (secondCall.data.bob) {
return res.redirect(/home);
}
} catch(e) {console.error(3)}
}
} catch(e) {console.error(e)}
next();
}
最佳答案
您可以使用一些最小的 api 将 req、res 和 next 作为空对象( stub ),并在您的函数运行后检查它们的更改。对于 stub /模拟/ spy ,您也可以使用现成的 sinon.js https://sinonjs.org或开玩笑
关于javascript - 单元测试异步 Express 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54392291/