Skip to content

Test Order Dependency

Error message

                Test passes alone but fails when run with other tests
              

Quick summary

The test depends on state left by other tests. When run alone it sets up its own state, but in the full suite, previous tests have modified shared state.

Why this happens

  • Shared mutable variables (arrays, objects) modified by tests without reset.

  • Database or file system state that persists between tests.

  • Mocks or spies not restored between tests.

  • Tests that depend on execution order.

Minimal example

✗ Broken code
let items = [];
test('test1', () => { items.push('a'); expect(items).toHaveLength(1); });
test('test2', () => { items.push('b'); expect(items).toHaveLength(1); }); // fails — items has 2
✓ Fixed code
let items;
beforeEach(() => { items = []; }); // reset before each test
test('test1', () => { items.push('a'); expect(items).toHaveLength(1); });
test('test2', () => { items.push('b'); expect(items).toHaveLength(1); }); // passes

Reset shared state in beforeEach so each test starts fresh.

How to diagnose

  • Run the failing test alone: npx jest --testPathPattern=<test-file> -t '<test-name>'.

  • If it passes alone, look for shared state — variables declared outside describe/test.

  • Check if beforeEach/afterEach properly resets state.

  • Run tests in random order (if supported) to expose order dependencies.

How to fix

  • Add beforeEach to reset shared state before each test.

  • Move shared variables inside the test or describe block.

  • Add afterEach to clean up mocks, spies, and database state.

  • Ensure each test sets up its own data instead of relying on other tests.

How to prevent

  • Always reset state in beforeEach — never rely on test execution order.

  • Keep tests isolated: each test should set up and tear down its own state.

  • Avoid shared mutable state outside of beforeEach/afterEach hooks.

Related Resources

Related Glossary

Related Lessons

← Back to language