BAE*_*BAE 4 javascript mocha.js promise
我正在阅读一些关于 mocha 承诺测试的教程。有一段代码:
before(function(done) {
return Promise.resolve(save(article)).then(function() {
done();
});
});
Run Code Online (Sandbox Code Playgroud)
为什么done()叫在then()中before()?上面的代码和下面的代码有什么区别:
before(function(done) {
return Promise.resolve(save(article));
});
Run Code Online (Sandbox Code Playgroud)
谢谢
更新
我的问题是与以下代码进行比较:
before(function() {
return Promise.resolve(save(article));
});
Run Code Online (Sandbox Code Playgroud)
抱歉打错字了。
带有before钩子的第一个代码片段返回一个 promise并调用done. 在 Mocha 3.x 及以上版本中,将导致此错误:
Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.
Run Code Online (Sandbox Code Playgroud)
过去,如果你使用done并返回一个 promise并没有特别重要,但最终 Mocha 开发人员认为同时指定done 并返回一个 promise 只是意味着测试设计者犯了一个错误,最好让 Mocha 更合适而不是而不是默默地允许。
在您的第二个代码段中,您有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);
});
});
Run Code Online (Sandbox Code Playgroud)
关于异步操作的完成,无论您使用的it是before、beforeEach、after还是afterEach,即使我给出的示例是 with it,它的工作方式都是一样的,这同样适用于所有钩子。
| 归档时间: |
|
| 查看次数: |
8762 次 |
| 最近记录: |