Skip to content

Mock 不 Called

错误信息

                Expected mock 函数到 有是 called, 但它 是不 called
              

快速摘要

assertion toHaveBeenCalled() 失败因为 mock 是从不 called. 你的 code path didn't 触发 expected 函数 call.

为什么发生

  • code under 测试 took 不同分支那个 doesn't call mocked 函数.

  • mock 是设置 on 错误对象 or 方法 name.

  • 函数是 called 之前 mock 是设置.

  • 测试输入 didn't 触发 code path 那个 calls 函数.

最小示例

✗ 错误代码
const mockFn = jest.fn();
test('calls callback', () => {
  // Code doesn't call mockFn because condition is false
  processData([], mockFn);
  expect(mockFn).toHaveBeenCalled(); // fails
});
✓ 修复代码
const mockFn = jest.fn();
test('calls callback', () => {
  // Provide data that triggers the callback
  processData([1, 2, 3], mockFn);
  expect(mockFn).toHaveBeenCalled(); // passes
});

Provide 测试输入那个触发 code path calling mock 函数.

如何诊断

  • 检查如果 mock 是设置 on 正确对象 and 方法 name.

  • Trace 通过 code 到 see 哪个分支是 taken 使用测试输入.

  • 添加 console.log in code 到 see 如果函数是 reached.

  • 检查如果 mock 是设置之前 code under 测试运行.

如何修复

  • Fix 测试输入到 触发 code path 那个 calls 函数.

  • 设置 mock 之前 calling code under 测试.

  • 验证 mock 是 on 正确对象 — 检查 spelling and 模块 paths.

  • 如果 code shouldn't call 函数 in 这个场景, 移除 assertion.

如何预防

  • 设置 mocks in beforeEach 到 ensure 它们're ready 之前每个测试.

  • Use 清晰测试数据那个 deterministically 触发 expected code paths.

相关资源

相关术语

相关课程

  • Mocking

    Using mocks 到 isolate code.

← 返回语言