debugjavascriptjestMajorpending
Debug: Jest tests pass individually but fail together
Viewed 0 times
test-isolationshared-stateorder-dependentmockbeforeEach
Error Messages
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:
jest --runInBand # Run serially to reproduce
jest --changedSince=main # Narrow down
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; });
// jest.config.js
{ maxWorkers: 1 } // Slowest but most isolated
- Find the culprit:
jest --runInBand # Run serially to reproduce
jest --changedSince=main # Narrow down
- 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; });
- Nuclear option: run in separate processes
// jest.config.js
{ maxWorkers: 1 } // Slowest but most isolated
Revisions (0)
No revisions yet.