done用于显式通知测试运行器异步操作完成,在Jest中用done(error)报错、Jasmine中用done.fail(error),而async/await可自动处理错误无需done。

在 JavaScript 异步测试中(尤其是使用 Jest 或 Jasmine 时),done 是一个回调函数,用于显式告诉测试运行器:异步操作已完成。若异步逻辑中抛出错误但未被 done 捕获或传递,测试可能超时失败,而非报出真实错误信息。
为什么要用 done 处理错误
直接在 setTimeout、Promise.then 或回调中 throw 错误,不会触发测试失败——因为错误发生在测试函数作用域之外。必须通过 done.fail()(Jasmine)或 done(error)(Jest)显式通知测试运行器发生了异常。
在 Jest 中正确使用 done 处理错误
Jest 的 done 接收一个可选的错误参数:done(error)。传入错误对象会标记测试为失败,并显示堆栈;调用 done()(无参)表示成功完成。
- ✅ 正确:在 Promise reject 或回调 error 中调用
done(err) - ❌ 错误:只写
throw err而不调用done(err) - ⚠️ 注意:不能同时调用
done()和done(err),否则报 “done called multiple times”
示例:
立即学习“Java免费学习笔记(深入)”;
Java Maven 项目审查工作流的通用输入处理。当 Java Maven 项目以 ZIP压缩包或 GitLab 仓库 URL 形式提供且需要...时使用。
test('fetchUser 应该返回用户数据', (done) => {
fetch('/api/user')
.then(res => res.json())
.then(data => {
expect(data.name).toBe('Alice');
done(); // 成功结束
})
.catch(err => {
done(err); // 关键:把错误传给 done
});
});
在 Jasmine 中使用 done.fail()
Jasmine 不接受 done(error),而是提供 done.fail(error) 方法来标记失败。
- ✅ 正确:使用
done.fail(err)报告异步错误 - ✅ 也可用
done.fail('message')传字符串 - ❌ 不要写
done(err),Jasmine 会忽略它
示例:
立即学习“Java免费学习笔记(深入)”;
it('should reject with 404 when user not found', function(done) {
fetch('/api/user/999')
.then(res => {
if (res.status !== 404) throw new Error('Expected 404');
done();
})
.catch(err => {
done.fail(err); // Jasmine 专用方式
});
});
更现代的替代方案:用 async/await
如果环境支持(Jest ≥27,Node.js ≥14),优先用 async/await 写法,无需手动管理 done,错误会自动冒泡到测试框架:
test('fetchUser works with async/await', async () => {
const res = await fetch('/api/user');
const data = await res.json();
expect(data.name).toBe('Alice');
}); // 错误自动被捕获,无需 done
只有在无法使用 async/await(如测试旧版 Node 回调 API)时,才需谨慎使用 done 并确保错误被正确传递。

















