Photo by Artem Sapegin on Unsplash
In a previous article I wrote about mocking methods on the request module.
request
also supports another workflow in which you directly call the imported module;
1var request = require('request');23request({4 method: 'GET',5 url: 'https://api.github.com/users/bulkan'6}, function(err, response, body){7 if (err) {8 return console.err(err);9 }1011 console.log(body);12});
You pass in an options object specifying properties like the HTTP method
to use and others such as url
, body
& json
.
Here is the example from the previous article updated to use request(options)
;
1var request = require('request');23function getProfile(username, cb){4 request({5 method: 'GET',6 url: 'https://api.github.com/users/' + username7 }, function(err, response, body){8 if (err) {9 return cb(err);10 }11 cb(null, body);12 });13}1415module.exports = getProfile;
Its not that big of a change. To unit test the getProfile
function we will need
to mock out request
module that is being imported by the module that getProfile
is defined in. This where mockery comes in.
It allows us to change what gets returned when a module is imported.
Here is a mocha test case using mockery. This assumes that the above code is in a file named gh.js
.
1var sinon = require('sinon')2 , mockery = require('mockery')3 , should = require('chai').should();45describe('User Profile', function(){6 var requestStub, getProfile78 before(function(){9 mockery.enable({10 warnOnReplace: false,11 warnOnUnregistered: false,12 useCleanCache: true13 });1415 requestStub = sinon.stub();1617 // replace the module `request` with a stub object18 mockery.registerMock('request', requestStub);1920 getProfile = require('./gh');21 });2223 after(function(){24 mockery.disable();25 });2627 it('can get user profile', function(done){28 requestStub.yields(null, {statusCode: 200}, {login: "bulkan"});2930 getProfile('bulkan', function(err, result){31 if(err) {32 return done(err);33 }34 requestStub.called.should.be.equal(true);35 result.should.not.be.empty;36 result.should.have.property('login');37 done();38 });39 });40})
mockery
hijacks the require
function and replaces modules with our mocks. In the above code
we register a sinon
stub to be returned when require('request')
is called. Then we configure
the mock in the test using the method .yield
on the stub to a call the callback
function passed to request
with null
for the error, an object for the response
and another object
for the body
.
You can write more tests
Hope this helps.