2017-08-08 51 views
1

我在閱讀some tutorials on promise tests in mocha。有一塊代碼:promise&mocha:done()之前還是不行?

before(function(done) { 
    return Promise.resolve(save(article)).then(function() { 
    done(); 
    }); 
}); 

爲什麼done()堪稱then()before()?是什麼上面的代碼和下面的代碼之間的區別:

before(function(done) { 
    return Promise.resolve(save(article)); 
}); 

感謝

UPDATE

我的問題是用以下代碼進行比較:

before(function() { 
    return Promise.resolve(save(article)); 
}); 

對不起爲錯字。

回答

1

帶有before掛鉤的第一個代碼段返回承諾調用done。在摩卡3.x和結束,這將導致該錯誤:

Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both. 

它曾經是,它並沒有特別重要,如果你使用done並返回一個承諾,但最終摩卡開發者計算過,同時指定done回覆諾言只是意味着測試設計師犯了一個錯誤,最好是讓摩卡適應而不是默默地允許它。

在您的第二個片段中,您有done參數並返回承諾,但Mocha仍會等待done被調用並且會超時。 (它真的應該檢測論點,並提出一個錯誤,就像第一種情況,但它不會......)

通常,如果您正在測試產生承諾的異步操作,那麼返回承諾比使用done更簡單。下面是說明問題的例子:

const assert = require("assert"); 

// This will result in a test timeout rather than give a nice error 
// message. 
it("something not tested properly", (done) => { 
    Promise.resolve(1).then((x) => { 
     assert.equal(x, 2); 
     done(); 
    }); 
}); 

// Same test as before, but fixed to give you a good error message 
// about expecting a value of 2. But look at the code you have to 
// write to get Mocha to give you a nice error message. 
it("something tested properly", (done) => { 
    Promise.resolve(1).then((x) => { 
     assert.equal(x, 2); 
     done(); 
    }).catch(done); 
}); 

// If you just return the promise, you can avoid having to pepper your 
// code with catch closes and calls to done. 
it("something tested properly but much simpler",() => { 
    return Promise.resolve(1).then((x) => { 
     assert.equal(x, 2); 
    }); 
}); 

至於異步操作的完成,無論您使用的是itbeforebeforeEachafterafterEach所以即使我給的例子是與工作原理相同it,這同樣適用於所有的掛鉤。

0

在這種特殊情況下,沒有功能差異。該回調函數通常被稱爲done,用於處理使用回調函數時的異步測試。返回Promise就足夠了,但請注意,您不能定義done回調,因爲測試套件將等待直到它被調用。當您無法輕鬆返回Promise時,請使用done。在你的情況下,第二個測試將是無限的,因爲你定義了done,你從未真正調用過。

0

我不確定我是否理解了100%的問題,但只有調用done才能開始測試。

beforeEach(function(done) { 
    setTimeout(function() { 
     value = 0; 
     done(); 
    }, 1); 
    }); 

直到在beforeEach上面的調用中調用done函數之後,纔開始該測試。這個規範直到完成被調用纔會完成。

it("should support async execution of test preparation and expectations", function(done) { 
    value++; 
    expect(value).toBeGreaterThan(0); 
    done(); 
    }); 

你不必在你的例子來一遍完成,只是:

before(function() { 
    return Promise.resolve(save(article)); 
}); 

如果通過done測試運行會想到之前調用繼續,否則它可能會拋出一個超時錯誤。

相關問題