如何在Promise上注册失败的Mocha测试

W.P*_*ill 11 javascript mocha.js promise chai

我正在编写返回promises的代码的Javascript Mocha单元测试.我正在使用Chai作为承诺的图书馆.我希望以下最小单元测试失败.

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);
    })
});
Run Code Online (Sandbox Code Playgroud)

当我运行此测试时,我看到打印到控制台的断言错误,但测试仍然算作传递.

> mocha test/spec.js 


  2+2
    ? should equal 5 
Unhandled rejection AssertionError: expected 4 to equal 5


  1 passing (10ms)
Run Code Online (Sandbox Code Playgroud)

如何编写此测试以使失败的断言导致测试计为失败?

pie*_*bot 23

对于其他任何因断言失败而没有通过promises进行单元测试失败的人,我知道你不应该传递done给函数.相反,只需返回承诺:

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

});
Run Code Online (Sandbox Code Playgroud)

这篇文章指出了我正确的方向.祝好运!


W.P*_*ill 10

我需要返回断言的结果.此测试按预期失败.

    it('should equal 5', function () {
        return four.should.eventually.equal(5);
    })
Run Code Online (Sandbox Code Playgroud)

  • 使用`Promise.all`来组合多个断言. (2认同)