Skip to content

Test Isolation

In one line

Test isolation means each test is self-contained — it doesn't depend on other tests' results or shared mutable state.

In simple words

Test isolation is the principle that tests should not affect each other. Each test should be able to run alone, in any order, and produce the same result.

Why isolation matters:

  • Parallel execution: Isolated tests can run in parallel for speed.
  • Debugging: If a test fails, you know it's because of that test, not because another test left bad state.
  • Reliability: No cascading failures where one test's failure causes others to fail.

Common violations of isolation:

  • Shared mutable variables that tests modify without resetting
  • Tests that depend on execution order
  • Database or file system state that persists between tests

The fix: use beforeEach to set up fresh state before every test, and afterEach to clean up. Each test should set up its own world and tear it down.

Example

javascript
// BAD: shared state
let counter = 0;
test('test1', () => { counter++; expect(counter).toBe(1); });
test('test2', () => { counter++; expect(counter).toBe(1); }); // fails if test1 ran first

// GOOD: isolated
beforeEach(() => { counter = 0; });
test('test1', () => { counter++; expect(counter).toBe(1); });
test('test2', () => { counter++; expect(counter).toBe(1); }); // always passes

The bad version shares state; the good version resets before each test for isolation.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary