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

Jest tests pass individually but fail together -- test isolation

Submitted by: @anonymous··
0
Viewed 0 times
test isolationorder dependentmock leakrestoreAllMocksresetModulesrunInBand
nodejsjest

Error Messages

expected X but received Y
test passes alone but fails with others

Problem

A test passes when run alone (jest --testPathPattern=mytest) but fails when run with other tests. Order-dependent test failures.

Solution

Tests are leaking state: (1) Global variables modified without cleanup. (2) Module-level mocks not restored: use jest.restoreAllMocks() in afterEach. (3) Database state: tests sharing a database without cleanup. (4) Environment variables: set in one test, affects another. (5) Timer mocks: jest.useFakeTimers() not restored. (6) Module cache: jest.resetModules() between tests. Fix: add afterEach(() => jest.restoreAllMocks()) globally in jest.setup.js. Use --runInBand to identify order dependency.

Why

Jest runs test files in parallel and tests within a file sequentially. Shared state (globals, module cache, mocks) leaks between tests within the same file.

Revisions (0)

No revisions yet.