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()
});
})
})
});
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); });
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.
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.
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);
});
});
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);
});
});
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