debugModeratepending
Jest tests pass individually but fail together -- test isolation
Viewed 0 times
test isolationorder dependentmock leakrestoreAllMocksresetModulesrunInBand
nodejsjest
Error Messages
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.