Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing promise callback in NodeJS with Mocha & Sinon

I am trying to test a method call that is returning a promise however I am having trouble. This in NodeJS code and I am using Mocha, Chai, and Sinon to run the tests. The test I currently have is:

it('should execute promise\'s success callback', function() {
  var successSpy = sinon.spy();

  mySpies.executeQuery = sinon.stub(databaseConnection, 'execute').returns(q.resolve('[{"id":2}]'));

  databaseConnection.execute('SELECT 2 as id FROM Users ORDER BY RAND() LIMIT 1').then(successSpy, function(){});

  chai.expect(successSpy).to.be.calledOnce;

  databaseConnection.execute.restore();
});

however this test is erroring with:

AssertionError: expected spy to have been called exactly once, but it was called 0 times

What is the proper way to test a method that is returning a promise?

like image 240
ryanzec Avatar asked Sep 02 '13 22:09

ryanzec


1 Answers

The handler of the then() call will not be called during registration - only during the next event loop, which is outside your current test stack.

You'll have to perform the check from within the completion handler and notify mocha that your asynchronous code has completed. See also http://visionmedia.github.io/mocha/#asynchronous-code

It should look something like this:

it('should execute promise\'s success callback', function(done) {
  mySpies.executeQuery = sinon.stub(databaseConnection, 'execute').returns(q.resolve('[{"id":2}]'));

  databaseConnection.execute('SELECT 2 as id FROM Users ORDER BY RAND() LIMIT 1').then(function(result){
    chai.expect(result).to.be.equal('[{"id":2}]');
    databaseConnection.execute.restore();
    done();
  }, function(err) {
    done(err);
  });
});

Changes to original code:

  • done parameter of the test function
  • check and cleanup within then() handler

Edit: Also, to be honest, this test is not testing anything regarding your code, it is only verifying the functionality of the promise, as the only bit of your code (the databaseConnection) is being stubbed out.

like image 121
dertseha Avatar answered Oct 04 '22 16:10

dertseha