因此,在一个文件中,我定义了这条路由:
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/