Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register a failed Mocha test on a Promise

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?

like image 959
W.P. McNeill Avatar asked May 22 '15 20:05

W.P. McNeill


People also ask

How do you test a rejected promise 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.

How do you skip the Mocha test?

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.

What is promise in Mocha?

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.


2 Answers

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!

like image 195
piercebot Avatar answered Oct 06 '22 00:10

piercebot


I needed to return the result of assertion. This test fails as expected.

    it('should equal 5', function () {
        return four.should.eventually.equal(5);
    })
like image 40
W.P. McNeill Avatar answered Oct 05 '22 22:10

W.P. McNeill