Mocha done()和异步等待的矛盾问题 [英] Paradoxical issue with mocha done() and async await
问题描述
我有以下测试案例:
it("should pass the test", async function (done) {
await asyncFunction();
true.should.eq(true);
done();
});
运行它会断言:
错误:解决方法指定过多.指定回调或 退还承诺;两者都不是.
Error: Resolution method is overspecified. Specify a callback or return a Promise; not both.
如果我删除了done();
语句,它将声明:
And if I remove the done();
statement, it asserts:
错误:超时超过2000毫秒.对于异步测试和挂钩,请确保 称为"done()";如果返回了Promise,请确保它可以解决.
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
如何解决这个矛盾?
推荐答案
您还需要删除done
参数,而不仅仅是调用它.像Mocha这样的测试框架会查看该函数的参数列表(或至少是其参数),以了解您使用的是done
还是类似的
You need to remove the done
parameter as well, not just the call to it. Testing frameworks like Mocha look at the function's parameter list (or at least its arity) to know whether you're using done
or similar.
使用Mocha 3.5.3,这对我有用(由于前者抛出错误,必须将true.should.be(true)
更改为assert.ok(true)
):
Using Mocha 3.5.3, this works for me (had to change true.should.be(true)
to assert.ok(true)
as the former threw an error):
const assert = require('assert');
function asyncFunction() {
return new Promise(resolve => {
setTimeout(resolve, 10);
});
}
describe('Container', function() {
describe('Foo', function() {
it("should pass the test", async function () {
await asyncFunction();
assert.ok(true);
});
});
});
但是如果我添加done
:
describe('Container', function() {
describe('Foo', function() {
it("should pass the test", async function (done) { // <==== Here
await asyncFunction();
assert.ok(true);
});
});
});
...然后我得到
错误:超时超过2000毫秒.对于异步测试和挂钩,请确保调用了"done()";如果返回了Promise,请确保它可以解决.
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
这篇关于Mocha done()和异步等待的矛盾问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!