![](/img/trans.png)
[英]How to test a “throwing an error” in Mocha having it in asyncronous code (read from db) using only callbacks (no promises, async/await)?
[英]How to test async code with mocha using await
如何使用 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();
});
});
这会产生以下错误:
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)
Mocha支持开箱即用的 Promises ; 你只需要将Promise return
到it()
的回调。
如果 Promise 解决,则测试通过。 相反,如果 Promise 拒绝,则测试失败。 就如此容易。
现在,由于async
函数总是隐式返回一个Promise
你可以这样做:
async function getFoo() {
return 'foo'
}
describe('#getFoo', () => {
it('resolves with foo', () => {
return getFoo().then(result => {
assert.equal(result, 'foo')
})
})
})
你不需要done
也不it
async
。
但是,如果您仍然坚持使用async/await
:
async function getFoo() {
return 'foo'
}
describe('#getFoo', () => {
it('returns foo', async () => {
const result = await getFoo()
assert.equal(result, 'foo')
})
})
在任何一种情况下,都不要将done
声明为参数
如果您使用上述任何方法,则需要从代码中完全删除done
。 将done
作为参数传递给it()
向 Mocha 暗示您打算最终调用它。
同时使用 Promises和done
将导致:
错误:解决方法被过度指定。 指定回调或返回 Promise; 不是都
done
方法仅用于测试基于回调或基于事件的代码。 如果您正在测试基于 Promise 或 async/await 的函数,则不应使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.