The React Testing Library Philosophy on Mocking
What you'll learn: How RTL's mocking philosophy aligns with testing user-visible behavior rather than implementation details.
The Guiding Principle
React Testing Library takes a strong stance on mocking: mock what your users don't see, avoid mocking what they interact with. This philosophy stems from RTL's core belief that tests should mirror how users experience your application.
RTL discourages mocking internal components, hooks, or application logic because these are implementation details. When you mock a child component or internal function, you're no longer testing the integrated behavior users actually experience—you're testing a fictional version of your app.
What to Mock (and What Not to Mock)
Mock external boundaries:
- Network requests (use MSW)
- Third-party libraries with side effects
- Browser APIs (like
Date, timers) - Expensive operations that don't affect user behavior
Don't mock internal code:
- Your own components
- Your custom hooks
- Application logic users interact with
- State management flows
The Confidence Gap
Think of your test suite as a contract with reality. Every mock creates a gap between what you're testing and what actually runs in production. RTL's philosophy minimizes these gaps by keeping mocks at the system's edges—where your app meets the outside world—while testing everything internal as an integrated whole.
When you mock a child component, you're essentially saying "I trust this works separately," but you lose confidence that parent and child work together correctly.
The Practical Result
This approach means more integration-style tests and fewer unit-style tests for UI code. You render real components with real children, using real hooks with real state, and mock only the network layer or browser APIs that are truly external.
Key Takeaway: RTL's mocking philosophy treats your application code as an integrated black box—mock external dependencies to control the test environment, but let your components, hooks, and logic interact naturally to build real confidence in user-facing behavior.