Mock External Dependencies, Not Internal Code
You'll learn the crucial distinction between what to mock (external APIs, third-party libraries) and what to keep real (your own components and hooks).
The Core Principle
When testing React components, mock at your application's boundaries, not within it. This means mocking HTTP calls to servers, third-party SDK methods, or browser APIs—but letting your own components, hooks, and utility functions run for real.
Think of your application as a house. You mock what comes through the doors and windows (electricity from the grid, water from the city), but you don't mock the wiring between rooms or the plumbing fixtures inside. Those internal connections need to work together authentically.
Why This Matters
Mocking your own code creates artificial test scenarios that don't reflect how your app actually runs. If you mock a custom hook while testing a component that uses it, you're not really testing that component—you're testing a fake version that never exists in production.
// ❌ BAD: Mocking internal hooks
vi.mock('./useUserData');
test('shows user profile', () => {
// This tests nothing real!
});
// ✅ GOOD: Mock the API, test everything else together
setupServer(
http.get('/api/user', () => {
return HttpResponse.json({ name: 'Alice' });
})
);
test('shows user profile', () => {
render(<UserProfile />); // useUserData runs for real
// ...
});
What to Mock
- HTTP requests (MSW handles this beautifully)
- Third-party APIs (analytics, payment SDKs)
- Browser APIs not available in jsdom (
localStorage,navigator.clipboard)
What NOT to Mock
- Your own components
- Your custom hooks
- Internal utility functions
- Redux reducers or Zustand stores
Key Takeaway: Mock at the edges of your application where you interact with the outside world, but test your own code as an integrated system—that's where real bugs hide.