The State Variable Antipattern
What you'll learn: Why directly testing internal state variables couples your tests to implementation details and destroys your ability to refactor safely.
The Tempting Trap
Imagine you're testing a toggle component. You could reach into the component's internals and assert expect(component.state.isOpen).toBe(true), but this is the state variable antipattern—testing how the component works instead of what the user sees.
When you test state directly, you're essentially writing tests that say "the component must use a variable called isOpen that equals true." But users don't care about variables. They care whether the menu appears on screen.
Why This Kills Refactoring
Let's say you refactor from useState to useReducer, or rename isOpen to expanded. Your component still works perfectly—the menu still opens—but all your tests break. You haven't broken user-facing behavior; you've only changed implementation.
This creates a vicious cycle: developers avoid refactoring because tests break, or they stop trusting tests because they break without real issues.
Test the Effect, Not the Cause
Instead of testing state variables, test their observable effects:
// ❌ Antipattern: testing state
expect(component.state.isOpen).toBe(true);
// ✅ Test behavior: what the user sees
expect(screen.getByRole('menu')).toBeInTheDocument();
The second approach doesn't care how the component tracks open/closed status. It only cares that the menu appears—which is all the user cares about too.
The Freedom to Change
State variables are an implementation detail. The component could use state, props, context, or derive the value from other data. Tests that avoid state variables remain valid through all these refactorings.
Key Takeaway: Testing state variables directly makes your tests brittle and prevents safe refactoring. Test the visible outcome of state changes, not the state itself—your tests should survive any internal restructuring that preserves user-facing behavior.