我将这个polyfill用于ES6 promise和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);
});
});
当我运行此测试时,由于超时而失败。在then块中抛出的断言失败在catch块中被捕获。我怎么能避免这种情况,直接扔给Mocha?
我可以直接从catch函数中抛出它,但我该如何为catch块做出断言呢?
如果Promise失败,它只会调用catch回调。因此,Mocha的done回调从未被调用,Mocha也从未发现Promise失败(因此等待并最终超时)。
您应该将console.log(err);
替换为done(err);
。当您将错误传递给done回调时,Mocha应该会自动显示错误消息。
我最终用Chai作为Promised解决了我的问题。
它允许你对承诺的解决和拒绝做出断言:
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是在成功或错误时完成的。
一个问题是,如果最后一个返回一些东西,那么我需要在then
和catch
:之前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)
})
*洛达什的套索()。
我很乐意听到任何对这种模式的批评。