如何使用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();
});
});
这将在下面产生错误:
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)
如果删除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)
答案 0 :(得分:5)
async
函数返回Promises
,因此您可以执行以下操作:
describe('test', function () {
it('should resolve', () => {
return callAsync();
});
});
摩卡supports Promises out-of-the-box,您只需要return
Promise。如果解决,则测试通过,否则将失败。
done
不需要async
或it
。
await
:下面是使用async
it
回调的示例。
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');
})
})
这两种情况均不需要done
。