When NOT to Mock: Testing Philosophy
What you'll learn: How to recognize when mocking undermines test confidence and when to prefer real implementations instead.
The Over-Mocking Trap
Just because you can mock something doesn't mean you should. Over-mocking creates tests that pass while your actual application breaks — defeating the entire purpose of testing. Your tests become green checkmarks that lie to you.
Think of it like testing a car: If you replace the engine with a fake one that always reports "running perfectly," your test will pass even when the real engine is broken. You've tested your mock, not your car.
When Mocking Obscures Reality
Avoid mocking when:
- The real implementation is fast and deterministic (pure functions, synchronous logic)
- Network calls can use MSW — Mock Service Worker intercepts at the network layer, not the module layer, testing your real fetch logic
- Components interact with real context/state — Mock the data source (API), not the stateful wrappers
- You're testing integration points — The value is in how pieces work together
Prefer Real Implementations
// ❌ BAD: Mocking the entire module obscures real behavior
vi.mock('./api', () => ({
fetchUser: vi.fn(() => Promise.resolve({ name: 'Test' }))
}))
// ✅ GOOD: Use MSW to intercept network, test real fetch logic
server.use(
http.get('/api/user', () => {
return HttpResponse.json({ name: 'Test' })
})
)
With MSW, your component runs its actual fetch code, handles responses, processes errors — just like production. You're testing the real chain, not a stand-in.
Key Takeaway: Mock external boundaries (APIs, timers), not your own code. When you mock too much, you test your imagination of how code works, not how it actually works.