unit testing - Node.js stubbing request.get() to call callback immediately -
i'm trying test function calls request.get()
function inside it.
i'm trying cover branches of callback function. i'm trying achieve without separating callback function different function because it's uses variables of upper closure.
here's example illustrate.. foo.js:
var request = require('request'); function func(arg1, arg2) { request.get({...}, function(error, response, body) { // stuff arg1 , arg2 // want covered if (...) { // want covered ... // want covered } else if (...) { // want covered ... // want covered } else { ... // want covered } }); } exports.func = func;
i tried stub sinon proxyquire.
foo.spec.js (stubbed 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 replace function calls callback not deal async operations in test foo.func(5, 3);
foo.spec.js (stubbed 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 replace function calls callback not deal async operations in test foo.func(5, 3);
neither did work. when tried debug never hit callback function, suggesting didn't stub request.get()
method correctly making still async operation. appreciate tell me did wrong in both scenarios (sinon & proxyquire) , examples on how fix it.
Comments
Post a Comment