node.js - 使用 mocha+sinon 测试 ExpressJS 路由时,如何 "stub"路由本地函数?

标签 node.js unit-testing express mocha.js sinon

因此,在一个文件中,我定义了这条路由:

router.post('/', security.authenticate, function(req, res, next) {
    //Doing prep stuff

    //Do database work (<< this is what im really testing for)

    //Calling another work function.
    createFormUser(req.body, (ret) => {
        return res.json(ret.createdUser);
    });

});

后面是这个函数:

var createFormUser = (ourUser, call) => {
    // does a bunch of misc work and creation for another database
    // unrelated to current tests.
}

我想测试一下这条路线。通常,我只会创建一个数据库的沙箱实例,以便它可以做任何它想做的事情,向测试中的路由发出 http 请求,最后在该 http 调用的返回中执行 Expects() 。

但是,我不想调用“createFormUser”函​​数,因为 1) 它做了一些奇特的事情,对于这个测试来说确实很难包含 2) 我将在其他地方测试它。

在正常测试中,我此时会使用 sinon 来 stub 该函数。但在本例中,我实际上没有对象引用,因为这都是通过向 mocha 在测试时后台打印的服务器发出 HTTP 请求来完成的。

所以我的问题与标题相同,如何 stub /替换/忽略/等此方法,以便在测试期间不会调用它?

最佳答案

正如 @DavidKnipe 所说,我所要做的就是通过以下方式导出方法:

module.exports.createFormUser = (ourUser, call) => { ... }

并且能够单独测试该方法并通过 sinon.stub 阻止其执行。

关于node.js - 使用 mocha+sinon 测试 ExpressJS 路由时,如何 "stub"路由本地函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40028440/

相关文章:

javascript - 动态命名空间 Socket.IO

node.js - 如何使用 Chai Http 发布对象数组

unit-testing - 如何在 Ansible 中进行单元测试?

unit-testing - 在 groovy 和 spock 中为不同的类运行相同的测试

javascript - 在expressjs中,如何限制可以同时发出请求的用户数量?

mysql - 无法使用express+mysql登录,注册有效

node.js - 登录生产最佳实践?

javascript - Aurelia npm 安装 : tons of "gyp ERR"

javascript - 使用 js-xlsx 编写日期列

unit-testing - c 程序的 Concolic 测试