I am writing Javascript Mocha unit tests on code that returns promises. I am using the Chai as Promised library. I expect the following minimal unit test to fail.
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
chai.should();
var Promise = require("bluebird");
describe('2+2', function () {
var four = Promise.resolve(2 + 2);
it('should equal 5', function () {
four.should.eventually.equal(5);
})
});
When I run this test, I see an assertion error printed to the console, but the test still counts as passing.
> mocha test/spec.js
2+2
✓ should equal 5
Unhandled rejection AssertionError: expected 4 to equal 5
1 passing (10ms)
How do I write this test so that a failed assertion causes the test to count as a failure?
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.
To skip multiple tests in this manner, use this.skip() in a “before all” hook: before(function() { if (/* check test environment */) { // setup code } else { this.skip(); } }); This will skip all it , beforeEach/afterEach , and describe blocks within the suite.
By returning the promise to Mocha, you ensure that Mocha waits for the async task to be completed before the assertions are run and the test is marked as complete.
For anybody else having trouble with failed assertions not failing unit tests with promises, I learned that you should NOT pass done
to the function. Instead, just return the promise:
it('should handle promises', function(/*no done here*/) {
return promiseFunction().then(function(data) {
// Add your assertions here
});
// No need to catch anything in the latest version of Mocha;
// Mocha knows how to handle promises and will see it rejected on failure
});
This article pointed me in the right direction. Good luck!
I needed to return the result of assertion. This test fails as expected.
it('should equal 5', function () {
return four.should.eventually.equal(5);
})
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