Expected 到 Throw 但做 不
错误信息
Expected 函数到 throw 错误, 但它 做不 throw
快速摘要
测试 expected code 到 throw 错误, 但它 didn't. 要么 code 应该 throw 但 doesn't (bug), or 测试 expectation 是错误.
为什么发生
code 是 supposed 到 throw 但 doesn't — missing 错误 handling.
输入 don't 触发错误条件.
错误是 caught internally and 不 re-thrown.
测试 expectation 是错误 — 函数 shouldn't throw in 这个场景.
最小示例
✗ 错误代码
function divide(a, b) {
return a / b; // doesn't throw on division by zero (returns Infinity)
}
test('throws on zero', () => {
expect(() => divide(1, 0)).toThrow(); // fails — no throw
});✓ 修复代码
function divide(a, b) {
if (b === 0) throw new Error('Division by zero');
return a / b;
}
test('throws on zero', () => {
expect(() => divide(1, 0)).toThrow('Division by zero');
});添加 missing throw 语句所以函数 properly 拒绝 division 通过零.
如何诊断
检查如果 code 有错误条件那个应该触发 throw.
验证测试输入 actually 触发错误 path.
检查如果 try/catch 内部函数 swallows 错误.
Review 函数's specification — 应该它 throw 在这种情况下?
如何修复
如果 code 应该 throw, 添加 missing throw 语句.
如果输入 don't 触发错误, use 输入那个做.
如果错误是 caught internally, re-throw 它 or 测试 caught behavior 相反.
如果函数 shouldn't throw, 移除 toThrow assertion.
如何预防
测试两者都成功 and 错误 paths for 函数那个能 throw.
Use 清晰错误消息当 throwing 到 aid 调试.
相关资源
相关术语
相关课程
- Assertions
Using assertions 到验证 behavior.