帶有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);
});
});
至於異步操作的完成,無論您使用的是it
,before
,beforeEach
,after
或afterEach
所以即使我給的例子是與工作原理相同it
,這同樣適用於所有的掛鉤。