vamsiampolu
vamsiampolu

Reputation: 6622

Testing promises with mocha chai and sinon

I would like to test my promise resolve handler and promise rejection handler using mocha,chai and sinon.In addition,I have got the sinon-chai plugin and sinon-stub-promise plugin set up.

This is my block of require statements:

var chai = require('chai');
var expect = chai.expect;
var sinonChai = require('sinon-chai');
chai.use(sinonChai);
var sinon = require('sinon');
var sinonStubPromise = require('sinon-stub-promise');
sinonStubPromise(sinon);

This is my test suite:

describe('Connect to github users',function(done){

    var api = require('../users'),
        onSuccess = api.onSuccess,
        onError = api.onReject; 
    console.dir(api);
    //the idea is not to test the async connection,the idea is to test 
    //async connection but to test how the results are handled.
    var resolveHandler,
        rejectHandler,
        getPromise,
        result;

    beforeEach(function(){
        resolveHandler = sinon.spy(onSuccess);
        rejectHandler = sinon.spy(onError);
        getPromise = sinon.stub().returnsPromise();
    });

    it('must obtain the result when promise is successful',function(){
        result = [...];//is an actual JSON array    
        getPromise.resolves(result);

        getPromise()
            .then(resolveHandler)
            .catch(rejectHandler);

        expect(resolveHandler).to.have.been.called();//error 
        expect(resolveHandler).to.have.returned(result);
        expect(rejectHandler).to.have.not.been.called();    
        done();
    });

    afterEach(function(){
        resolveHandler.reset();
        rejectHandler.reset();
        getPromise.restore();
    });

});

I find myself getting this error:

 Connect to github users must obtain the result when promise is successful:
 TypeError: expect(...).to.have.been.called.toEqual is not a function
  at Context.<anonymous> (C:\Users\vamsi\Do\testing_promises\test\githubUsersSpec.js:94:46)

Upvotes: 2

Views: 2362

Answers (2)

Ethan O Brien
Ethan O Brien

Reputation: 36

The sinon-with-promise package should fit the bill for what you're trying to do. I ran into the same problem (except I didn't need to test reject cases) and it worked out nicely.

Upvotes: 0

vamsiampolu
vamsiampolu

Reputation: 6622

This line of code here is wrong:

expect(resolveHandler).to.have.been.called();

called is just a property on the spy whose value is always a boolean and can be simply tested using chai like this:

expect(resolveHandler.called).to.equal(true);

Similarly instead of this line to confirm that the function has not rejected:

expect(rejectHandler).to.have.not.been.called();

Use this with called as a property:

expect(rejectHandler.called).to.equal(false);

Upvotes: -1

Related Questions