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.
# 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 3Common 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 (or vitest test: {})
module.exports = {
clearMocks: true,
restoreMocks: true,
resetModules: true,
};Surface the dependency with random order
- Run with
--shuffle(Jest) /--sequence.shuffle(Vitest) to expose order coupling. - Isolate shared singletons behind a factory you re-create in
beforeEach. - Restore globals like
process.envyou mutate, inafterEach.
How to prevent it
- Enable
clearMocks/restoreMocksand reset globals in teardown. - Run tests in randomized order in CI to catch coupling early.
- Avoid module-level mutable singletons in code under test.