HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavascriptjestMajorpending

Debug: Jest tests pass individually but fail together

Submitted by: @anonymous··
0
Viewed 0 times
test-isolationshared-stateorder-dependentmockbeforeEach

Error Messages

expected X but received Y
test passes alone fails in suite
order dependent

Problem

Tests pass when run individually (jest --testPathPattern=...) but fail when run as a suite. Order-dependent test failures.

Solution

This indicates shared mutable state between tests:

  1. Find the culprit:


jest --runInBand # Run serially to reproduce
jest --changedSince=main # Narrow down

  1. Common causes:


a) Global state not reset:
// BAD: module-level mutable state
let cache = {};
// FIX: Reset in beforeEach or use jest.isolateModules
beforeEach(() => { cache = {}; });

b) Mock not restored:
// BAD: jest.spyOn without restore
// FIX:
afterEach(() => jest.restoreAllMocks());
// Or in jest.config:
{ restoreMocks: true }

c) Database/file state leaking:
// FIX: Use transactions, rollback after each test
beforeEach(() => db.beginTransaction());
afterEach(() => db.rollbackTransaction());

d) Timers not cleaned:
afterEach(() => jest.useRealTimers());

e) Environment variables modified:
const originalEnv = process.env;
beforeEach(() => { process.env = { ...originalEnv }; });
afterEach(() => { process.env = originalEnv; });

  1. Nuclear option: run in separate processes


// jest.config.js
{ maxWorkers: 1 } // Slowest but most isolated

Revisions (0)

No revisions yet.