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;

Copy 1 var request = require ( 'request' ) ; 2 3 request ( { 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 } 10 11 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) ;

Copy 1 var request = require ( 'request' ) ; 2 3 function getProfile ( username , cb ) { 4 request ( { 5 method : 'GET' , 6 url : 'https://api.github.com/users/' + username 7 } , function ( err , response , body ) { 8 if ( err ) { 9 return cb ( err ) ; 10 } 11 cb ( null , body ) ; 12 } ) ; 13 } 14 15 module . 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 .

Copy 1 var sinon = require ( 'sinon' ) 2 , mockery = require ( 'mockery' ) 3 , should = require ( 'chai' ) . should ( ) ; 4 5 describe ( 'User Profile' , function ( ) { 6 var requestStub , getProfile 7 8 before ( function ( ) { 9 mockery . enable ( { 10 warnOnReplace : false , 11 warnOnUnregistered : false , 12 useCleanCache : true 13 } ) ; 14 15 requestStub = sinon . stub ( ) ; 16 17 18 mockery . registerMock ( 'request' , requestStub ) ; 19 20 getProfile = require ( './gh' ) ; 21 } ) ; 22 23 after ( function ( ) { 24 mockery . disable ( ) ; 25 } ) ; 26 27 it ( 'can get user profile' , function ( done ) { 28 requestStub . yields ( null , { statusCode : 200 } , { login : "bulkan" } ) ; 29 30 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.