第一个带有before钩子的代码sn-p返回一个promise并且调用done。在 Mocha 3.x 及以上版本中,会导致此错误:
Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.
过去,如果你使用 done 并返回一个 Promise 并不重要,但最终 Mocha 开发人员认为同时指定 done 和返回一个 Promise 只是意味着测试设计师犯了一个错误,最好让 Mocha 调整一下,而不是默默地允许它。
在您的第二个 sn-p 中,您有 done 参数并返回一个承诺,但 Mocha 仍将等待 done 被调用并超时。 (它确实应该检测到参数并像第一种情况一样引发错误,但它没有......)
一般来说,如果您正在测试一个产生 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 或afterEach,它的工作原理都是一样的,所以即使我给出的示例是@987654335 @,同样适用于所有的钩子。