[英]How to test async code with mocha using await
How do I test async code with mocha?如何使用 mocha 测试异步代码? I wanna use multiple
await
inside mocha我想在 mocha 中使用多个
await
var assert = require('assert');
async function callAsync1() {
// async stuff
}
async function callAsync2() {
return true;
}
describe('test', function () {
it('should resolve', async (done) => {
await callAsync1();
let res = await callAsync2();
assert.equal(res, true);
done();
});
});
This produces error below:这会产生以下错误:
1) test
should resolve:
Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.
at Context.it (test.js:8:4)
If I remove done() I get:如果我删除 done() 我得到:
1) test
should resolve:
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/tmp/test/test.js)
Mocha supports Promises out-of-the-box ; Mocha支持开箱即用的 Promises ; You just have to
return
the Promise to it()
's callback.你只需要将Promise
return
到it()
的回调。
If the Promise resolves then the test passes.如果 Promise 解决,则测试通过。 In contrast, if the Promise rejects then the test fails.
相反,如果 Promise 拒绝,则测试失败。 As simple as that.
就如此容易。
Now, since async
functions always implicitly return a Promise
you can just do:现在,由于
async
函数总是隐式返回一个Promise
你可以这样做:
async function getFoo() {
return 'foo'
}
describe('#getFoo', () => {
it('resolves with foo', () => {
return getFoo().then(result => {
assert.equal(result, 'foo')
})
})
})
You don't need done
nor async
for your it
.你不需要
done
也不it
async
。
However, if you still insist on using async/await
:但是,如果您仍然坚持使用
async/await
:
async function getFoo() {
return 'foo'
}
describe('#getFoo', () => {
it('returns foo', async () => {
const result = await getFoo()
assert.equal(result, 'foo')
})
})
In either case, do not declare done
as an argument在任何一种情况下,都不要将
done
声明为参数
If you use any of the methods described above you need to remove done
completely from your code.如果您使用上述任何方法,则需要从代码中完全删除
done
。 Passing done
as an argument to it()
hints to Mocha that you intent to eventually call it.将
done
作为参数传递给it()
向 Mocha 暗示您打算最终调用它。
Using both Promises and done
will result in:同时使用 Promises和
done
将导致:
Error: Resolution method is overspecified.
错误:解决方法被过度指定。 Specify a callback or return a Promise;
指定回调或返回 Promise; not both
不是都
The done
method is only used for testing callback-based or event-based code. done
方法仅用于测试基于回调或基于事件的代码。 You shouldn't use it if you're testing Promise-based or async/await functions.如果您正在测试基于 Promise 或 async/await 的函数,则不应使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.