Reputation: 1
I have implement node js code to call HTTP API's using request module. For get, post, put, delete, I have directly called request() of require module,
var sendRequest = function(req, callback) {
request(req, function(err, res) {
if (err) {
callback(err, null, res);
} else {
callback(null, res);
}
}
}
I want to invoke sendRequest() but mock the response of request(). Any pointers for this.
Upvotes: 0
Views: 662
Reputation: 21
One way to get it stubbed without anything but sinon, is to stub the inner class of Request, which conveniently offers its prototype, like this
stub = sinon.stub(request.Request.prototype, "init");
stub.callsFake( options => options.callback(null, {statusCode: 200}, "faked response"));
Where options
in the callsFake
are processed by the request
function and the passed into the Request.prototype.init
.
Now your callback parameters, are the ones expected in your var sendRequest = function(req, callback) {...}
function
Upvotes: 2
Reputation: 6128
One of the many options is to use proxyquire to stub the request module:
var proxyquire = require('proxyquire')
, assert = require('assert')
, requestStub = function (req, callback) { callback(req); };
// assuming you export the sendRequest from that file
var sendRequest = proxyquire('./sendRequest', { 'request': pathStub });
describe('sendRequest', function() {
it('request', function (done) {
var someReq = {a: 'b'};
sendRequest(someReq, function (req) {
assert.equal(someReq, req);
done();
});
});
});
Upvotes: 0