Skip to content

Fake Timer Not Restored

Error message

                Real timers were used after fake timers were not restored
              

Quick summary

Fake timers were enabled but never restored to real timers, causing time-related issues in subsequent tests.

Why this happens

  • jest.useFakeTimers() called without corresponding jest.useRealTimers().

  • No afterEach hook to restore real timers.

  • Fake timers leak into other test files.

Minimal example

✗ Broken code
test('test1', () => {
  jest.useFakeTimers();
  // ... test logic ...
  // missing jest.useRealTimers()
});
test('test2', () => {
  setTimeout(() => {}, 1000); // affected by fake timers from test1
});
✓ Fixed code
afterEach(() => jest.useRealTimers());
test('test1', () => {
  jest.useFakeTimers();
  // ... test logic ...
});
test('test2', () => {
  setTimeout(() => {}, 1000); // uses real timers — restored
});

Restore real timers in afterEach to prevent fake timers from leaking.

How to diagnose

  • Look for jest.useFakeTimers() without jest.useRealTimers().

  • Check if there's an afterEach(() => jest.useRealTimers()).

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

  • Check if setTimeout/setInterval behave unexpectedly in later tests.

How to fix

  • Add afterEach(() => jest.useRealTimers()) to restore real timers after each test.

  • Or call jest.useRealTimers() at the end of the test.

  • Configure Jest with restoreMocks: true and clearTimers: true.

How to prevent

  • Always restore real timers in afterEach when using fake timers.

  • Or use beforeEach/afterEach pairs for fake timer setup and teardown.

Related Resources

Related Lessons

← Back to language