问题描述
我正在使用mocha
练习基本的单元测试用例,并对 HOW 和 When 有点困惑,以使用 done()处理程序.
I am practicing basic unit test cases with mocha
and a bit confused HOW and WHEN to use done() handler.
- 如何使用
done()
?
下面是我无法使用done
的示例代码:
Below is my sample code where I am not able to use done
:
it('Testing insertDocumentWithIndex', async (done) => {
try{
var data = await db.insertDocumentWithIndex('inspections', {
"inspectorId" : 1,
"curStatus" : 1,
"lastUpdatedTS" : 1535222623216,
"entryTS" : 1535222623216,
"venueTypeId" : 1,
"location" : [
45.5891279,
-45.0446183
]
})
expect(data.result.n).to.equal(1);
expect(data.result.ok).to.equal(1);
}
catch(e){
logger.error(e);
done(e);
}
})
我跑步时失败,并引发错误-
When I run, it fails and throws an error-
但是,只有在失败的情况下才应调用done
(原谅我,如果我说的是错误的话,我是初学者),这是我在catch
块中所做的,并返回到第二个返回Promise的地方,效果很好.参见下面的代码
But done
should be called in case of failure only(forgive me if I am saying something incorrect, I am a beginner), which I have done in catch
block and coming to the second point of returning a Promise, well that works fine. See below code
it('Testing insertDocumentWithIndex', async () => {
return new Promise(async (resolve, reject) => {
try{
var data = await db.insertDocumentWithIndex('inspections', {
"inspectorId" : 1,
"curStatus" : 1,
"lastUpdatedTS" : 1535222623216,
"entryTS" : 1535222623216,
"venueTypeId" : 1,
"location" : [
45.5891279,
-45.0446183
]
})
expect(data.result.n).to.equal(1);
expect(data.result.ok).to.equal(1);
resolve()
}
catch(e){
reject(e);
}
})
});
但这需要附加的Promise构造代码,但这不是问题.但这提出了另一个问题
But this requires an additional Promise construction code, not a problem though. But it raises another question
- 何时应使用
done
?
对使用mocha
编写测试用例的更好方法的任何帮助或建议都将有所帮助.
Any help or suggestion for a better approach for writing test cases with mocha
will help.
推荐答案
正确的方法是不要将done
与async..await
一起使用. Mocha支持诺言,并且能够链接从it
等函数返回的诺言. async
函数是始终返回promise的函数的语法糖:
The correct way is to not use done
with async..await
. Mocha supports promises and is able to chain a promise that is returned from it
, etc. functions. And async
function is syntactic sugar for a function that always returns a promise:
it('Testing insertDocumentWithIndex', async () => {
var data = await db.insertDocumentWithIndex('inspections', {
"inspectorId" : 1,
"curStatus" : 1,
"lastUpdatedTS" : 1535222623216,
"entryTS" : 1535222623216,
"venueTypeId" : 1,
"location" : [
45.5891279,
-45.0446183
]
})
expect(data.result.n).to.equal(1);
expect(data.result.ok).to.equal(1);
})
仅在测试异步API时才需要
done
,而不涉及承诺.即便如此,兑现承诺通常也会带来更清晰的控制流程.
done
is needed only for testing asynchronous APIs than don't involve promises. Even then, converting to promises often results in cleaner control flow.
还有这个
it('Testing insertDocumentWithIndex', async () => {
return new Promise(async (resolve, reject) => {
...
是promise构造反模式,由于async
promise构造函数回调,这一点甚至更糟.
is promise construction antipattern, which is even worse because of async
promise constructor callback.
这篇关于在通过Mocha测试asc/await时正确使用done()的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!