Skip to content
Latchkey

Jest/Vitest Flaky Order-Dependent Tests - Pass Alone, Fail Together

A test passes when run alone but fails inside the full suite (or vice versa). That is shared state leaking between tests: an unreset module/mock, global state, or an implicit dependency on execution order.

What this error means

Tests are green individually with -t/a single file, but the full run fails - or fails only when sharded differently in CI. The failure moves around as you change order, the signature of state leakage.

CI log
# passes alone
$ jest src/cart.test.ts        # PASS

# fails in the full suite (random order)
$ jest --shuffle               # FAIL src/cart.test.ts: expected 0, received 3

Common causes

Shared mutable state not reset

A module-level cache, singleton, or global (e.g. process.env, a shared array) is mutated by one test and read by another, so the outcome depends on what ran first.

Mocks or modules not restored

A jest.mock/vi.mock or spy set in one test leaks into the next because clearMocks/restoreMocks is off and no afterEach resets it.

How to fix it

Reset state and mocks between tests

jest.config.js
// jest.config.js (or vitest test: {})
module.exports = {
  clearMocks: true,
  restoreMocks: true,
  resetModules: true,
};

Surface the dependency with random order

  1. Run with --shuffle (Jest) / --sequence.shuffle (Vitest) to expose order coupling.
  2. Isolate shared singletons behind a factory you re-create in beforeEach.
  3. Restore globals like process.env you mutate, in afterEach.

How to prevent it

  • Enable clearMocks/restoreMocks and reset globals in teardown.
  • Run tests in randomized order in CI to catch coupling early.
  • Avoid module-level mutable singletons in code under test.

Frequently asked questions

What causes "Order-dependent flake"?
A module-level cache, singleton, or global (e.g. process.env, a shared array) is mutated by one test and read by another, so the outcome depends on what ran first.
How do I fix Order-dependent flake?
Reset state and mocks between tests

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card