繁体   English   中英

摩卡的ES6承诺

[英]ES6 Promises in Mocha

我正在使用这种polyfill用于ES6承诺和Mocha / Chai。

我对这些承诺的断言是行不通的。 以下是一个示例测试:

it('should fail', function(done) {
    new Promise(function(resolve, reject) {
        resolve(false);
    }).then(function(result) {
        assert.equal(result, true);
        done();
    }).catch(function(err) {
        console.log(err);
    });
});

当我运行此测试时,由于超时而失败。 在块中引发的断言失败在catch块中被捕获。 我怎么能避免这种情况,直接把它扔到摩卡?

我可以从catch函数中抛出它,但那么我将如何为catch块进行断言?

如果您的Promise出现故障,它只会调用您的catch回调。 结果,Mocha的完成回调从未被调用过,而Mocha从未发现Promise失败了(所以它等待并最终超时)。

你应该替换console.log(err); done(err); 将错误传递给完成回调时,Mocha应自动显示错误消息。

我最终通过使用Chai作为承诺来解决我的问题。

它允许您对承诺的解决和拒绝做出断言:

  • return promise.should.become(value)
  • return promise.should.be.rejected

我在Mocha / Chai / es6-promise测试中使用的模式如下:

it('should do something', function () {

    aPromiseReturningMethod(arg1, arg2)
    .then(function (response) {
        expect(response.someField).to.equal("Some value")
    })
    .then(function () {
        return anotherPromiseReturningMethod(arg1, arg2)
    })
    .then(function (response) {
        expect(response.something).to.equal("something")
    })
    .then(done).catch(done)

})

最后一行很奇怪,但是在成功或出错时调用了Mocha。

一个问题是如果最后一个返回一些东西,那么我需要在thencatch之前使用noop()*:

it('should do something', function () {

    aPromiseReturningMethod(arg1, arg2)
    .then(function (response) {
        expect(response.someField).to.equal("Some value")
    })
    .then(function () {
        return anotherPromiseReturningMethod(arg1, arg2)
    })
    .then(_.noop).then(done).catch(done)

})

* Lodash的noop()。

很想听听对这种模式的批评。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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