Skip to content

Unhandled Promise Rejection in 测试

错误信息

                UnhandledPromiseRejectionWarning: 错误 in 测试
              

快速摘要

异步操作拒绝 (threw 错误) 但测试 didn't catch 它. 这个能 cause 测试到 通过不正确地 or crash unexpectedly.

为什么发生

  • 异步函数拒绝但 测试 doesn't use try/catch or .拒绝.

  • Promise 是创建但 不 awaited or returned, 所以 rejection 是 unhandled.

  • mock 是设置使用 mockResolvedValue 但 code calls 拒绝函数.

  • Missing 等待 on 异步 call 那个能 拒绝.

最小示例

✗ 错误代码
test('handles error', async () => {
  // Missing rejection handling
  const result = await fetchData(); // if this rejects, unhandled
  expect(result).toBeDefined();
});
✓ 修复代码
test('handles error', async () => {
  await expect(fetchData()).rejects.toThrow('Network error');
});

Use .拒绝.toThrow() 到 properly handle and 测试 Promise rejections.

如何诊断

  • Look for 异步操作不使用等待 or .catch().

  • 检查如果 mocks 是设置到 拒绝当 测试 expects 成功.

  • Use expect.assertions(1) 到 ensure 测试 actually 运行 assertions.

  • 添加 try/catch or use .拒绝.toThrow() for expected rejections.

如何修复

  • For expected rejections: 等待 expect(asyncFn()).拒绝.toThrow('错误消息').

  • Or use try/catch: try { 等待 asyncFn(); 失败('应该有 thrown'); } catch (e) { expect(e.消息).toBe('...'); }

  • Ensure 所有 Promise 是 awaited or returned 从测试.

  • Fix mock 设置到 match expected behavior (resolve 对比拒绝).

如何预防

  • 总是等待 or 返回 Promise in 测试.

  • Use .拒绝.toThrow() for 测试 expected rejections.

  • 启用 --unhandled-rejections=strict in 节点.js 到 catch 这些 early.

相关资源

相关课程

← 返回语言