8

When testing async code with Mocha and one of my asserts fails, all Mocha does is to report a timeout error. Is there a way to improve this? How to know what asserts failed 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.

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()
      });
    })
  })
});
1
  • Try to set a higher timeout for this specific test with a this.setTimeout(10000), just to make sure it's not just a matter of how long your getContacts() is taking to finish. Commented May 31, 2015 at 19:09

3 Answers 3

6

The issue is that the assertion fails, which throws an exception. This causes the promise to be rejected, but there isn't anyone to notice. Your code only checks if the promise succeeds. If you return the promise, then mocha will check for it and fail the 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);
    });
}); 
Sign up to request clarification or add additional context in comments.

Comments

2

You should return the promise like this:

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

Comments

1

It seems like when the assert throws an error that error is swallowed and never shown and also the code after assert throws is skipped.

Try like this (catching the reject):

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 of then(null, rejectFunc) use catch(rejectFunc) with libs like bluebird.

Also the answer by idbehold is great. I didn't know yet that mocha supports promises directly and I always use the done param knowing if I have a timeout without a stack trace there was a swallowed error in this test.

2 Comments

It is to handle the situations like "false positive". Isn't it @IIiyan ?
@muneermuhammed Yes, exactly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.