Avoiding Test Interdependence
You'll learn how to ensure each test runs independently, preventing mysterious failures when test order changes.
The Problem with Interdependent Tests
Test interdependence occurs when one test relies on side effects or state left behind by another test. This creates fragile test suites where tests pass or fail depending on execution order—a debugging nightmare. Each test should be a self-contained unit that sets up its own preconditions and cleans up afterward.
Think of tests like hotel rooms: each guest (test) should find the room (state) in pristine condition, regardless of who stayed there previously.
Common Causes of Interdependence
Shared mutable state is the primary culprit. This includes:
- Global variables modified during tests
- Database records created but not cleaned up
- Module-level caches or singletons
- DOM elements left behind in browser tests
- File system changes not reverted
Writing Independent Tests
Use beforeEach() to reset state before every test:
describe('Shopping cart', () => {
let cart;
beforeEach(() => {
// Fresh cart for EVERY test
cart = createEmptyCart();
});
it('should add items', () => {
cart.add('apple');
expect(cart.items.length).toBe(1);
});
it('should calculate total', () => {
// This test doesn't depend on the previous test
cart.add('banana');
expect(cart.total()).toBe(1.5);
});
});
Each test creates its own cart rather than sharing one. If you run only the second test, or run them in reverse order, they still pass.
Verification Strategy
Periodically run tests in random order or isolation. If a test fails alone but passes in the suite, you've found interdependence.
Key Takeaway: Each test must establish its own setup and leave no trace behind—independent tests are reliable tests that can run in any order without affecting each other.