Spy 不 Restored
错误信息
Another 测试失败因为 spy 是不 restored
快速摘要
spy replaced 真实函数但 是从不 restored, 所以 spy persists 到 other 测试, causing unexpected behavior.
为什么发生
jest.spyOn 是 called 但 spy.mockRestore() 是从不 called.
否 afterEach Hook 到 restore mocks 之间测试.
jest.restoreAllMocks() 是不 配置 in afterEach.
spy 是创建内部测试但 不 cleaned 上.
最小示例
test('test1', () => {
jest.spyOn(console, 'log').mockImplementation(() => {});
// spy not restored — affects test2
});
test('test2', () => {
console.log('hello'); // silently swallowed by spy from test1
});afterEach(() => jest.restoreAllMocks());
test('test1', () => {
jest.spyOn(console, 'log').mockImplementation(() => {});
});
test('test2', () => {
console.log('hello'); // works normally — spy restored
});添加 afterEach 到 restore 所有 mocks, preventing spies 从 leaking 之间测试.
如何诊断
Look for jest.spyOn calls 不使用 corresponding mockRestore().
检查如果那里's afterEach(() => jest.restoreAllMocks()) in 测试 file.
运行测试 in isolation 到 see 如果失败是 顺序-dependent.
添加 console.log 到 see 如果 spied 函数是 still mocked in later 测试.
如何修复
添加 afterEach(() => jest.restoreAllMocks()) 到 restore 所有 mocks 之后每个测试.
Or call spy.mockRestore() explicitly at 端的 测试.
Use beforeEach 到设置 spies fresh for 每个测试.
如何预防
总是添加 afterEach(() => jest.restoreAllMocks()) 当 using spies.
Or 配置 Jest 使用 restoreMocks: 真 in jest.配置.js.
相关资源
相关术语
相关课程
- Stubs and Spies
理解测试 doubles.