簡體   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