如何使用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();
});
});
Run Code Online (Sandbox Code Playgroud)
这将产生以下错误:
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)
Run Code Online (Sandbox Code Playgroud)
如果删除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)
Run Code Online (Sandbox Code Playgroud)
Nik*_*des 11
async函数返回,Promises因此您可以执行以下操作:
describe('test', function () {
it('should resolve', () => {
return callAsync();
});
});
Run Code Online (Sandbox Code Playgroud)
Mocha supports Promises out-of-the-box, you just have to return the Promise. If it resolves then the test passes otherwise it fails.
You don't need done nor async for your it.
await:And here's an example using async it callbacks.
async function getFoo() {
return 'foo'
}
async function getBar() {
return 'bar'
}
describe('Foos and Bars', () => {
it('#returns foos and bars', async () => {
var foo = await getFoo()
assert.equal(foo, 'foo');
var bar = await getBar()
assert.equal(bar, 'bar');
})
})
Run Code Online (Sandbox Code Playgroud)
done as an argumentIf you use any of the methods described above you need to remove done completely from your code. Passing done as an argument to it() hints to Mocha that you intent to eventually call it.
| 归档时间: |
|
| 查看次数: |
6100 次 |
| 最近记录: |