Testing User Behavior, Not Implementation
What you'll learn: How to write tests that focus on what users experience rather than how your component works internally.
The Philosophy Shift
React Testing Library (RTL) enforces a fundamental principle: test your components like a user would interact with them. This means you should query elements by their accessible labels or text content, not by internal implementation details like component state, props, or CSS classes.
Think of it like testing a car. A user cares that pressing the brake pedal stops the car—they don't care whether it uses hydraulic fluid or electronic signals internally. Similarly, users care that clicking a button shows a modal, not that isOpen state changed to true.
What This Looks Like in Practice
❌ Testing Implementation (avoid this):
- Checking if
useStateholds a specific value - Asserting props were passed correctly
- Querying by CSS class names or test IDs unnecessarily
- Testing component methods directly
✅ Testing User Behavior (do this):
- Clicking a button and verifying text appears on screen
- Typing into an input and seeing the result
- Checking that elements are visible or hidden
- Verifying accessible roles and labels
Why This Matters
When you test implementation details, your tests break whenever you refactor—even if user-facing behavior stays identical. If you rename a state variable or switch from useState to useReducer, implementation-focused tests fail despite nothing changing for users.
Testing behavior makes your tests resilient to refactoring and aligned with actual user value.
Key Takeaway: Write tests that could pass even if you completely rewrote the component's internal logic, as long as the user experience remains the same. Test what users see, read, click, and type—not your component's internals.