I'm trying to test a function which calls request.get()
function inside it.
What I'm trying is to cover all branches of the callback function. I'm trying to achieve it without separating the callback function to a different function because it's uses variables of the upper closure.
Here's an example to illustrate.. foo.js:
var request = require('request');
function func(arg1, arg2) {
request.get({...}, function(error, response, body) {
// do stuff with arg1 and arg2 // want to be covered
if (...) { // want to be covered
... // want to be covered
} else if (...) { // want to be covered
... // want to be covered
} else {
... // want to be covered
}
});
}
exports.func = func;
I tried to stub it with sinon as well as proxyquire.
foo.spec.js (stubbed with sinon):
var foo = require('./foo'),
var sinon = require('sinon'),
var request = require('request');
var requestStub = sinon.stub(request, 'get', function(options, callback) {
callback(new Error('Custom error'), {statusCode: 400}, 'body');
}); // Trying to replace it with a function that calls the callback immediately so not to deal with async operations in test
foo.func(5, 3);
foo.spec.js (stubbed with proxyquire):
var requestStub = {};
var proxyquire = require('proxyquire'),
var foo = proxyquire('./foo', {'request': requestStub}),
var sinon = require('sinon');
requestStub.get = function(options, callback) {
callback(new Error('Custom error'), {statusCode: 400}, 'body');
}; // Trying to replace it with a function that calls the callback immediately so not to deal with async operations in test
foo.func(5, 3);
Neither did work. When I tried to debug I never hit the callback function, which is suggesting that I didn't stub the request.get()
method correctly making it still async operation.
I would appreciate someone tell me what I did wrong in both scenarios (sinon & proxyquire) and examples on how to fix it.