How to check a validation error in Mocha when testing asynchronous code

When testing asynchronous code using Mocha and one of my statements fails, all Mocha is a timeout error message. Is there any way to improve this? How to find out what claims failure and why?

mocha Contact #getContacts() 1) should return at least 1 contact 0 passing (3s) 1 failing 1) Contact #getContacts() should return at least 1 contact: Error: timeout of 3000ms exceeded. Ensure the done() callback is being called in this test. 

the code:

 var assert = require("assert"); var contact = require("../lib/contact.js"); var chai = require('chai'); var should = chai.should(); describe('Contact', function() { describe('#getContacts()', function() { it('should return at least 1 contact', function(done) { contact.getContacts().then(function(contacts) { assert.equal(4,2) done() }); }) }) }); 
+7
mocha
source share
3 answers

The problem is that the statement fails, which raises an exception. This makes us promise to be rejected, but no one noticed. Your code only checks if the promise is fulfilled. If you return the promise, Mocha will check it and not test if the promise is rejected.

So you want

 it('should return at least 1 contact', function() { return contact.getContacts().then(function(contacts) { assert.equal(4,2); }); }); 
+6
source share

You must return the promise as follows:

 it('should return at least 1 contact', function() { return contact.getContacts().then(function(contacts) { assert.equal(4,2); }); }); 
+2
source share

It looks like when assert throws an error, skipped and never displayed, as well as code after assert throws is skipped.

Try this (catch the deviation):

 it('should return at least 1 contact', function(done) { contact.getContacts().then(function(contacts) { assert.equal(4,2) done() }).then(null, function (err) { console.error(err); done(err); }); }) 

Or instead (null, rejectFunc) use catch (rejectFunc) with libs like bluebird.

And the answer from idbehold is great. I did not know yet that mocha supports promises directly, and I always use the parameter made, knowing if I have a timeout without a stack trace, there was a swallowed error in this test.

+1
source share

All Articles