Missing 做() 回调 in 异步测试
错误信息
测试 finished 之前异步回调已完成 — 做() 不 called
快速摘要
测试 uses 做回调模式但 forgets 到 call 做() 内部异步回调. Jest marks 测试 as 完整之前 assertion 运行.
为什么发生
做参数是 declared 但做() 是从不 called.
做() 是 called in 错误位置 (e.g., 之前 assertion).
错误 in 回调 prevents 做() 从是 reached.
Mixing 异步/等待使用做 回调不正确地.
最小示例
✗ 错误代码
test('callback test', (done) => {
fetchData((data) => {
expect(data).toBe('result');
// missing done() — Jest finishes early
});
});✓ 修复代码
test('callback test', (done) => {
fetchData((data) => {
expect(data).toBe('result');
done(); // signal test completion
});
});Call 做() 之后所有 assertions 到 tell Jest 异步测试是 完整.
如何诊断
检查如果测试函数 takes '做' 参数.
验证做() 是 called at 端的 异步回调, 之后所有 assertions.
检查如果错误 in 回调 prevent 做() 从是 called.
Consider 切换到 异步/等待哪个 doesn't 需要做().
如何修复
Call 做() 之后所有 assertions in 回调: 回调((数据) => { expect(数据).toBe(...); 做(); }).
Handle 错误: 回调((err, 数据) => { 如果 (err) { 做(err); 返回; } expect(数据).toBe(...); 做(); }).
Prefer 异步/等待 over 做回调 — 它's cleaner and 更少错误-prone.
如何预防
Prefer 异步/等待 for 异步测试 — avoid 做回调模式.
如果 using 做(), 总是 call 它 in 每个 code path (包含错误 paths).
相关资源
相关课程
- 异步测试
测试 asynchronous code.