第一个代码片段带有before
钩子返回一个承诺and calls done
。在 Mocha 3.x 及以上版本中,会导致以下错误:
Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.
过去,如果您使用过,这并不特别重要done
并返回了一个承诺,但最终 Mocha 开发人员认为指定两者done
and返回承诺只意味着测试设计者犯了一个错误,最好让 Mocha 配合,而不是默默地允许它。
在你的第二个片段中,你有done
争论并返回一个承诺,但 Mocha 仍会等待done
被调用并且会超时。 (它确实应该检测参数并像第一种情况一样引发错误,但它没有......)
通常,如果您正在测试产生 Promise 的异步操作,则返回 Promise 比使用 Promise 更简单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
or afterEach
所以即使我给出的例子是it
,这同样适用于所有钩子。