javascript - 单元测试异步 Express 中间件

标签 javascript node.js express asynchronous testing

我有以下异步中间件,它使用多个 try-catch 来检查某些 http 调用的响应。我希望对这个中间件进行单元测试,但在模拟“下一个”回调时遇到了困难。当我这样包装它时:

it('should test for auth', () => {
    logon(req, res, function() {
        expect(res.locals).toBe(true)
    })
})

它似乎并没有实际运行该函数并在之后运行 expect。关于如何模拟 requestresponsenext 对象以便测试最终值 (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/

相关文章:

node.js - 如何将 NodeJs 应用程序部署到 azure Web 应用程序

javascript - 如何在 div 打开/隐藏时更改图标

javascript - 通过 AJAX Web API 存在参数时无法发布

javascript - 发布 Asp.net 网站后的 CSS 和 JS 文件有垃圾字符

javascript - 为什么我的循环在迭代之间不等待?设置超时()

node.js - Heroku 部署 - "Push rejected, failed to compile Node.js app"

javascript - Gulp 似乎可以正常工作,但尚未处理构建文件

node.js - 如何在CompoundJS中通过 "use"方法传递参数?

javascript - Express 路由与 AngularJS 路由冲突。

node.js - 本地安装express-generator