Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check assertion error in Mocha when testing async code

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()
      });
    })
  })
});
like image 798
Ricardo Mayerhofer Avatar asked May 31 '15 18:05

Ricardo Mayerhofer


People also ask

How do you test async in mocha?

Writing Asynchronous Tests with Mocha. To indicate that a test is asynchronous in Mocha, you simply pass a callback as the first argument to the it() method: it('should be asynchronous', function(done) { setTimeout(function() { done(); }, 500); });

How do you test async function in Chai?

we practically combine all the solution ( async/await , promise based and callback done ) for async test in the test file. Let's use the recent solution using async/await so it will be: describe('testing users ', () => { it('can get all users', async () => { const response = await chai.

How do you test your promises in mocha?

Create a file named teams. js, import the API using require and create the function getTeamByPlayer it will return a promise, using setTimeout simulate the async process. Our promise return the resolve if the team with the player is found or the reject with an error if not found. Export the function to be used.


2 Answers

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);
    });
}); 
like image 80
David Norman Avatar answered Oct 21 '22 15:10

David Norman


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);
  });
});
like image 33
idbehold Avatar answered Oct 21 '22 14:10

idbehold