Andrey Byelogurov Andrey Byelogurov - 1 month ago 5
Node.js Question

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.

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.

In a normal test I would at this point use sinon to stub the function. 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.

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?

Answer

As stated by @DavidKnipe, all I had to do was export the methods via:

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

And was able to both test the method individually and prevent it's execution via a sinon.stub.

Comments