javascript - 如何在 Mocha 异步单元测试中使用 afterEach?
问题描述
在下面的代码中,在测试中的 Promise 被解析并被afterEach()
调用之前done()
被调用。我希望它在测试完成后运行done()
。这样做的正确方法是什么?
describe ("Some test", ()=>{
afterEach(()=>{
console.log("Done")
})
it("Does something", done=>{
new Promise (resolve=>{
let result = doSomething();
assert.isOK(result);
done();
})
})
})
解决方案
这不是你在 Mocha 中使用 Promises 的方式。
Mocha 仅通过返回 Promise(不需要done()
)或使用async
函数作为测试(隐式返回 Promise)来支持异步测试,如下所示:
describe ("Some test", ()=>{
afterEach(()=>{
console.log("Done")
})
it("Does something", async () => {
const result = await someAsyncFunction();
assert.isOK(result);
// no need to return from this one, async functions always return a Promise.
})
})
或者
describe ("Some test", ()=>{
afterEach(()=>{
console.log("Done")
})
it("Does something", done=>{
// note the return
return new Promise (resolve=>{
doSomethingWithCallback(result => {
assert.isOK(result);
resolve(result);
});
})
})
})
请注意,new Promise()
在非低级代码中使用构造函数被视为反模式。有关更多详细信息,请参阅此问题:什么是显式承诺构造反模式以及如何避免它?
推荐阅读
- regex - 带有“大于”的 SUMIF 数组公式
- tableau-api - Tableau 不会从数据源 (.txt) 导入所有记录
- deployment - dotnet 3.1 定位程序集的清单定义与程序集引用不匹配
- javascript - JSON.Stringify 在对对象数组进行字符串化时返回空数组
- react-native - 排毒不起作用 [Info.plist 不包含 CFBundleShortVersionString]
- java - 两台服务器分别用于 HTML 和 Java Jersey Rest API 或单个 Tomcat Webapp
- node.js - 导入 `express` 库需要数百毫秒。有没有办法加快这个过程?
- ios - 如何从另一个 UIView 类访问 UIControl 的值
- json - 解组 JSON 保留空值
- javascript - 在父子组件中保持状态(复选框和复选框)