简体   繁体   中英

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?

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

Expanding on @piercebot answer, I am using chai-as-promised to resolve the promise like this:

var chai = require('chai');
var expect = chai.expect;
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised); 

...

it('should handle promises', function() {    
  return promiseFunction().then(function(res) {
    expect(Promise.resolve(res)).to.eventually.equals(true);
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM