Testing Call Answers in NodeJS with Mocha & Sinon

I am trying to test a method call that returns a promise, but I have problems. This is in NodeJS code, and I use Mocha, Chai and Sinon to run the tests. The test I have is:

it('should execute promise\ 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 a mistake:

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

What is the correct way to test a method that returns a promise?

+4
source share
2 answers

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

You will need to perform a check inside the completion handler and notify mocha that your asynchronous code has completed. See Also http://visionmedia.imtqy.com/mocha/#asynchronous-code

It should look something like this:

 it('should execute promise\ 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 in the source code:

  • made test function parameter
  • validation and cleaning in the then () handler

Edit: Also, to be honest, this test does not test anything regarding your code, it only checks the functionality of the promise, since only a bit of your code (databaseConnection) breaks.

+7
source

I recommend checking out Mocha As Promised.

It allows you to use a cleaner syntax than trying to do done() and all this nonsense.

 it('should execute promise\ success callback', function() { var successSpy = sinon.spy(); mySpies.executeQuery = sinon.stub(databaseConnection, 'execute').returns(q.resolve('[{"id":2}]')); // Return the promise that your assertions will wait on return databaseConnection.execute('SELECT 2 as id FROM Users ORDER BY RAND() LIMIT 1').then(function() { // Your assertions expect(result).to.be.equal('[{"id":2}]'); }); }); 
+1
source

Source: https://habr.com/ru/post/1500212/


All Articles