Navigate back to the homepage

Mocking a function that returns a (bluebird) Promise

Bulkan Evcimen
April 28th, 2014 · 1 min read

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

1var Promise = require('bluebird');
2
3module.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;

1var db = require('./db');
2
3module.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;

1var db = require('./db')
2 , should = require('chai').should()
3 , sinon = require('sinon')
4 , users;
5
6describe('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 its to resolve.

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

Hope this helps.

More articles from Bulkan

Testing With Mocha, Sinon.js & Mocking Request

Photo by Louis Hansel @shotsoflouis on Unsplash Introduction Writing tests with Mocha is really fun and satisfying. Combined with should.js…

October 7th, 2013 · 2 min read

Using Twython To Connect To The Twitter Streaming API via OAuth

Photo by Benjamin Balázs on Unsplash Before you can connect to the Streaming API you need create a Twitter application. This will give you…

August 3rd, 2013 · 1 min read
© 2007–2020 Bulkan
Link to $https://twitter.com/bulkanevcimenLink to $https://github.com/bulkanLink to $https://instagram.com/bulkan.evcimen