Testing State Changes Through Their Effects
What you'll learn: How to verify that state updates work correctly by testing what the user sees or experiences, rather than inspecting internal state variables.
The Wrong Instinct
When testing components, it's tempting to peek inside and check if count === 5 or if isOpen === true. But remember: users can't see your state variables. They only see the DOM, read text, click buttons, and experience side effects.
The Right Approach: Test the Effect, Not the Cause
Instead of asserting on state directly, verify what changed in the UI as a result of that state update.
Example scenario: A toggle button that shows/hides content.
Bad test thinking:
- "After clicking,
isVisibleshould betrue"
Good test thinking:
- "After clicking, the hidden content should appear on screen"
Why This Matters
State is an implementation detail. Tomorrow, you might refactor from useState to useReducer, or derive the value instead of storing it. If your test checks state directly, it breaks even though the user experience is identical.
By testing effects (DOM changes, text appearing, elements becoming disabled, focus shifting), your tests:
- Remain valid through refactors
- Match how users actually interact
- Catch real bugs that affect UX
The Mental Model
Think of your component as a vending machine. You don't care about the internal gears and counters—you only care that when you insert a coin and press B3, you get your candy bar. State is the gears. The DOM is the candy bar.
Key Takeaway: Always verify state updates by asserting on their observable effects—what appears, disappears, or changes in the DOM—never by inspecting state variables directly.