Course contentsShow
← React
Lesson 2085 of 2,39646. Testing React with RTLFree lesson

Why MSW Over Manual Mocks

MSW works in tests and dev, avoids brittle module mocks, and mirrors production fetch patterns.

Why MSW Over Manual Mocks

What you'll learn: Why Mock Service Worker (MSW) is superior to manual module mocks for testing network requests in React applications.

The Problem with Manual Mocks

When you use vi.mock() to mock fetch or axios, you're testing a fake implementation that only exists in your test environment. Your production code uses the real network layer with different edge cases, error handling, and timing characteristics. This creates a confidence gap: passing tests don't guarantee your code works in production.

Manual mocks also tightly couple your tests to implementation details. If you switch from fetch to axios, or refactor your API layer, all your mocks break. You're not testing user behavior—you're testing internal wiring.

MSW's Advantages

Works in both tests AND development: MSW uses Service Workers to intercept actual HTTP requests. The same mock definitions run in your test suite and your local development environment. This means you're testing the real fetch flow, just with a different destination.

Mirrors production patterns: Your component still calls fetch() or axios.get(). The request travels through the network stack, gets intercepted by MSW, and returns a mocked response. This tests error boundaries, loading states, and retry logic exactly as they'll behave in production.

Avoids brittle module mocks: MSW mocks at the network boundary, not the module level. You can refactor your data fetching layer freely—as long as the HTTP requests stay the same, your tests continue working. It's implementation-agnostic.

The Mental Model

Think of MSW as a test double for your API server, not a mock of your JavaScript modules. You're replacing the backend, not your frontend code.

Key Takeaway: MSW provides higher test confidence by intercepting real network requests rather than mocking modules, works identically in tests and development, and remains stable when you refactor your data fetching implementation.