Mock Implementation 不正确
错误信息
Mock returned unexpected 值 — 测试 assertion 失败
快速摘要
mock's 返回值 doesn't match 什么测试 expects. mock 设置 (mockReturnValue, mockResolvedValue) 有错误值.
为什么发生
mockReturnValue or mockResolvedValue 是 given 错误值.
mock implementation doesn't match 真实函数's behavior.
mock 是 reconfigured 之间测试不使用 resetting.
mockImplementationOnce 是 used 但 mock 是 called 更多次数 than 配置.
最小示例
const mockFetch = jest.fn().mockResolvedValue({ id: 1 });
test('gets user', async () => {
const user = await getUser(5);
expect(user.id).toBe(5); // fails — mock always returns id: 1
});test('gets user', async () => {
mockFetch.mockResolvedValue({ id: 5 }); // match expected id
const user = await getUser(5);
expect(user.id).toBe(5);
});配置 mock 到返回正确值 那个 matches 测试 expectation.
如何诊断
检查 mock 设置 — 做 mockReturnValue/mockResolvedValue 返回正确值?
验证 mock 是 called expected 数字的 次数.
检查如果 mockReset() or mockClear() 是需要之间测试.
Compare mock's 返回值 到什么真实函数会 返回.
如何修复
Fix mock 返回值 到 match 什么测试 expects.
Use mockImplementation for 更多复杂 mock behavior.
添加 mockReset() in beforeEach 到 ensure clean mock 状态.
Use mockResolvedValueOnce for sequential 不同返回值.
如何预防
Review mock 设置 carefully — mock 应该返回 realistic 测试数据.
Use beforeEach 到 reset mocks 之间测试.