Photo by Zdeněk Macháček on Unsplash

With Sinon.JS mocking functions are quite easy. Here is how to stub a function that returns a Promise.

Demonstrated with a potato quality example. Imagine the following code is in a file named db.js

Copy 1 var Promise = require ( 'bluebird' ) ; 2 3 module . exports . query = function query ( q ) { 4 return Promise . resolve ( [ 5 { 6 username : 'bulkan' , 7 verified : true 8 } 9 ] ) 10 }

Using bluebird we simulate a database query which returns a Promise that is resolved with an Array of Objects.

Imagine the following code located in users.js ;

Copy 1 var db = require ( './db' ) ; 2 3 module . exports . getVerified = function getVerified ( ) { 4 return db . query ( 'select * from where verified=true' ) ; 5 }

The mocha unit test for the above which stubs out db.query that is called in users.js ;

Copy 1 var db = require ( './db' ) 2 , should = require ( 'chai' ) . should ( ) 3 , sinon = require ( 'sinon' ) 4 , users ; 5 6 describe ( 'Users' , function ( ) { 7 var sandbox , queryStub ; 8 9 beforeEach ( function ( ) { 10 sandbox = sinon . sandbox . create ( ) ; 11 queryStub = sandbox . stub ( db , 'query' ) ; 12 users = require ( './users' ) ; 13 } ) ; 14 15 afterEach ( function ( ) { 16 sandbox . restore ( ) ; 17 } ) ; 18 19 it ( 'getVerified should return a resolved Promise' , function ( ) { 20 queryStub . returns ( Promise . reject ( 'still resolved' ) ) ; 21 var p = users . getVerified ( ) ; 22 p . isResolved ( ) . should . be . true ; 23 return p ; 24 } ) ; 25 } )

In the beforeEach and afterEach functions of the test we create a sinon sandbox which is slightly over kill for this example but it allows you to stub out a few methods without worrying about manually restoring each stub later on as you can just restore the whole sandbox as demonstrated in the afterEach .

There is one test case that tells the queryStub to return a Promise that is rejected. Then test that the promise that users.getVerified returns is resolved. Mocha now will wait until Promises that are returned from it s to resolve.

Sorry about the potato quality example, been trying to think of a better example. Any suggestions ?

Hope this helps.