Skip to content

Spy Not Restored

Error message

                Another test failed because a spy was not restored
              

Quick summary

A spy replaced a real function but was never restored, so the spy persists into other tests, causing unexpected behavior.

Why this happens

  • jest.spyOn was called but spy.mockRestore() was never called.

  • No afterEach hook to restore mocks between tests.

  • jest.restoreAllMocks() is not configured in afterEach.

  • The spy was created inside a test but not cleaned up.

Minimal example

✗ Broken code
test('test1', () => {
  jest.spyOn(console, 'log').mockImplementation(() => {});
  // spy not restored — affects test2
});
test('test2', () => {
  console.log('hello'); // silently swallowed by spy from test1
});
✓ Fixed code
afterEach(() => jest.restoreAllMocks());
test('test1', () => {
  jest.spyOn(console, 'log').mockImplementation(() => {});
});
test('test2', () => {
  console.log('hello'); // works normally — spy restored
});

Add afterEach to restore all mocks, preventing spies from leaking between tests.

How to diagnose

  • Look for jest.spyOn calls without corresponding mockRestore().

  • Check if there's an afterEach(() => jest.restoreAllMocks()) in the test file.

  • Run tests in isolation to see if the failure is order-dependent.

  • Add console.log to see if the spied function is still mocked in later tests.

How to fix

  • Add afterEach(() => jest.restoreAllMocks()) to restore all mocks after each test.

  • Or call spy.mockRestore() explicitly at the end of the test.

  • Use beforeEach to set up spies fresh for each test.

How to prevent

  • Always add afterEach(() => jest.restoreAllMocks()) when using spies.

  • Or configure Jest with restoreMocks: true in jest.config.js.

Related Resources

Related Glossary

Related Lessons

← Back to language