简体   繁体   English

使用mocha + sinon测试ExpressJS路由时,如何“存根”该路由本地的函数?

[英]When testing an ExpressJS route using mocha+sinon, how do you “stub” a function that's local to the route?

So in one file, I have this route defined: 因此,在一个文件中,我定义了以下路由:

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);
    });

});

followed by this function: 接下来是这个功能:

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

I want to to test this route. 我想测试这条路线。 Normally, I would just create a sandbox instance of the database so that it can do whatever it wants, make an http request to the route in the test, and finally do expects() in the return from that http call. 通常,我只是创建数据库的沙箱实例,以便它可以执行所需的任何操作,向测试中的路由发出http请求,最后在该http调用的返回值中执行Expects()。

However, I don't want the "createFormUser" function to be called, because 1) it does some fancy shit that's really hard to contain for this test 2) I will be testing it elsewhere. 但是,我不希望调用“ createFormUser”函​​数,因为1)它执行了一些花哨的东西,对于此测试来说确实很难包含。2)我将在其他地方对其进行测试。

In a normal test I would at this point use sinon to stub the function. 在正常测试中,我此时将使用sinon对函数进行存根。 But in this case I don't actually have an object reference, since this is all done through HTTP requests to server that mocha spools up when testing. 但是在这种情况下,我实际上没有对象引用,因为所有这些都是通过对服务器的HTTP请求完成的,该服务器在测试时会将Mocha假脱机。

So my question is the same as the title, how can stub/replace/ignore/etc this method so it doesn't get called during the test? 所以我的问题和标题一样,如何对这个方法进行存根/替换/忽略/等,以便在测试期间不会被调用?

As stated by @DavidKnipe, all I had to do was export the methods via: 如@DavidKnipe所述,我要做的就是通过以下方式导出方法:

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

And was able to both test the method individually and prevent it's execution via a sinon.stub. 并能够分别测试该方法并通过sinon.stub阻止其执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM