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?
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With