skip to content

Why would a Jest 30 order-service test pass alone but fail after the other tests in its file, and how do you trace and fix the leftover mock state?

level: seniorimportance: should knowfreq 50%

answer

  1. state lives as long as the file
  2. counts inflated by a neighbour
  3. unconsumed queues and live spies
  4. shuffle with a fixed seed

basics

~20 s

Mocks live for the whole test file, so call records, unused Once values, implementations and installed spies carry into later tests. Reproduce with --randomize and a seed, compare the mock's state, then reset in beforeEach or enable clearMocks with restoreMocks.

solid answer

~40 s

Within one file, Jest builds the module registry and its mocks once, and nothing cleans them between tests unless `clearMocks`, `resetMocks` or `restoreMocks` is set; all three default to `false`. So a later test can see an inflated `toHaveBeenCalledTimes` count, a `mockRejectedValueOnce` an earlier test queued but never consumed, an implementation another test installed, or a spy that was never restored. Re-spying does not help: `jest.spyOn` on a method that is already a mock returns the same spy, record included. I reproduce it by running the test alone with `-t`, then the file with `--randomize --seed`, and print `mock.calls` where it fails. The fix is making cleanup automatic: `clearMocks` plus `restoreMocks`, or `resetMocks` with behaviour set in `beforeEach`. In Jest 30.5, `restoreMocks` alone leaves plain `jest.fn()` mocks untouched.

code

javascript · 4 lines
javascript
module.exports = {
  clearMocks: true,
  restoreMocks: true,
};

go deeper

for a junior

Know that a mock keeps its calls and behaviour across tests in the same file unless something clears it.

for a middle

List what each of clearMocks, resetMocks and restoreMocks removes, and why module-scope setup can be wiped by them.

for a senior

Reproduce the failure with -t and --randomize with a seed, name the exact store that leaked, and fix it with config plus beforeEach setup rather than ad hoc mockClear calls.

for a principal

Turn the fix into a suite-wide rule for mock config and test setup, and decide how to roll it out when many existing tests quietly depend on leaked state.

## Why state survives between tests Each Jest test file runs with its own **module registry**. Every `jest.mock`, every module-scope `jest.fn()` and every spy is created once for that file and then shared by all of its tests. Jest does not clean them between tests by default: `clearMocks`, `resetMocks` and `restoreMocks` all default to `false`. A test that passes alone and fails after its neighbours therefore usually inherits something one of them left on a mock. The leak stays inside the file; another file gets a fresh registry and fresh mocks. ## The usual culprits When the order service's tests share a mocked payment client and a spied logger, these are the leftovers to look for: 1. **An accumulated record.** `expect(paymentClient.charge).toHaveBeenCalledTimes(1)` fails with a received count of 3 because two earlier tests also charged. 2. **An unconsumed `...Once` value.** A test queues `mockRejectedValueOnce(new Error('card_declined'))` but takes an early-return path that never calls `charge`; the rejection waits in the queue and fails the next test's first charge. `clearMocks` does not remove it, because it clears only the record. 3. **A replaced default.** One test calls `mockImplementation` or `mockResolvedValue` to simulate an outage, and every later test still gets the outage. 4. **A spy that was never restored.** `jest.spyOn(logger, 'error').mockImplementation(() => {})` stays on the shared logger. Calling `jest.spyOn` again in the next test does not start over: on a method that is already a mock it returns that same mock, with its old calls still recorded. 5. **State inside a mocked module.** A factory or manual mock that keeps a counter or a cache keeps it for the whole file, since the factory runs once per registry. The opposite failure exists too: with `resetMocks` or `restoreMocks` switched on, a default or spy set up at module scope or in `beforeAll` is wiped before the first test runs, and **every** test fails, not just some. ## Reproducing it reliably - Run the failing test alone with `-t` (`--testNamePattern`) to confirm it passes in isolation. - Run the file with `--randomize`, which shuffles test order within the file, and note the seed it prints; `--seed=<num>` replays exactly that order. - At the failing assertion, log `charge.mock.calls`, `charge.mock.results` and `jest.isMockFunction(logger.error)` to see which state arrived from earlier. - Remember that `--runInBand` changes only how files are scheduled across workers; tests inside one file already run one after another, in declared order unless `--randomize` is set, so it neither causes nor hides this kind of leak. ## Fixing it | Approach | What it covers | Watch out for | |---|---|---| | `clearMocks: true` | call records of every mock | keeps implementations and queued `...Once` values | | `resetMocks: true` | records and all implementations | wipes module-scope defaults; spies stay installed, returning `undefined` | | `restoreMocks: true` | puts spied and replaced originals back | in Jest 30.5, leaves plain `jest.fn()` mocks untouched | | `beforeEach` setup | builds each test's behaviour from scratch | must be kept in step with every new mock | A robust combination for this order service: - Set `clearMocks: true` and `restoreMocks: true` in the config, so records are always empty and spies are always detached. - In `beforeEach`, call `mockReset()` on shared module mocks and set their happy-path default, then let each test add its own `...Once` behaviour on top. - Create spies in `beforeEach` or in the test, never at module scope, so the restore that runs before each test does not remove them early. Where the code under test takes its collaborators as arguments, a small helper that returns fresh `jest.fn()` mocks for every test removes the shared state altogether, at the price of passing the payment client and logger in explicitly. ## Jest 30 details that change the diagnosis - `jest.restoreAllMocks()` in Jest 30.5 only runs the restore functions of spies and `jest.replaceProperty` replacements; a plain `jest.fn()` keeps its record and implementation. A suite that relied on `restoreMocks` to clear everything needs `clearMocks` or `resetMocks` as well. - `mockReset()` and `resetAllMocks` also clear `whenCalledWith` registrations, added in Jest 30.5, so per-argument behaviour does not leak once a reset runs. - The order-dependence itself is a general test-design problem; the Jest-specific part is knowing which of these stores holds the leftover and which key or hook clears it.

  • Why does adding jest.spyOn(logger, 'error') to beforeEach not give each test a fresh call record?
    If the previous test's spy was never restored, `logger.error` is already a mock, and `jest.spyOn` returns that existing mock instead of wrapping it again. Its calls carry over. Restore spies after each test, with `restoreMocks: true` or `jest.restoreAllMocks()` in `afterEach`, or clear them, so the next `spyOn` starts clean.
  • Could a leftover mock from one Jest test file break a test in a different file?
    Not through mock state: each test file gets its own module registry, so `jest.mock` registrations, module-scope mocks and spies on module exports exist only in that file. Cross-file failures point elsewhere, such as a shared database, files on disk or environment variables the tests change.

  • Each Jest test gets a fresh module registry, so mocks cannot leak between tests in a file.
  • A mock's leftover state can spill into another test file running in a parallel worker.
  • clearMocks: true stops an unused mockRejectedValueOnce from reaching the next test.
  • Calling jest.spyOn again in beforeEach always creates a new spy with an empty record.
  • Running with --runInBand fixes order-dependent mock failures inside one file.

Assumes Jest 30.5 or later: restoreAllMocks only restores spies and replaced properties, and whenCalledWith, cleared by mockReset, exists since 30.5.