Skip to content

Test isolation failure: shared state between tests

Quick summary

Your tests share state — one test modifies data that affects another test's outcome depending on execution order.

Why this happens

  • Tests modify a shared module-level variable or singleton without resetting it

  • A test leaves the database or mock in a dirty state that affects subsequent tests

  • Global configuration is changed in one test and not restored in afterEach

Minimal example

✗ Broken code
let count = 0;
test('increments', () => { count++; expect(count).toBe(1); });
test('checks count', () => { count++; expect(count).toBe(1); }); // fails if run after first test
✓ Fixed code
test('increments', () => {
  let count = 0;
  count++;
  expect(count).toBe(1);
});
test('checks count', () => {
  let count = 0;
  count++;
  expect(count).toBe(1);
});

Using local variables in each test instead of shared state ensures each test is independent and order does not matter.

How to diagnose

  • Run the failing test in isolation and then with the full suite to detect order dependence

  • Review beforeEach/afterEach hooks to verify state is properly reset

  • Check for module-level variables or singletons that tests modify without cleanup

How to fix

  • Add afterEach or beforeEach hooks to reset shared state between tests

  • Use local variables in each test instead of shared module-level state

  • Create fresh instances of objects or databases for each test with setup/teardown hooks

How to prevent

  • Always reset shared state in afterEach and avoid module-level mutable variables in tests

  • Use test-specific setup that creates fresh data for each test rather than sharing state

Related Resources

Related Glossary

Related Lessons

← Back to language