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

What MSW Is: Service Worker-Based Mocking

MSW intercepts requests at the network level, mocking fetch/XHR without changing component code.

What MSW Is: Service Worker-Based Mocking

You'll learn what Mock Service Worker (MSW) is and how it intercepts network requests without touching your component code.

The Core Concept

Mock Service Worker (MSW) is a network mocking library that works by intercepting requests at the network level using Service Workers (in browsers) or Node's request interception (in tests). Unlike traditional mocking approaches where you mock fetch() or specific modules, MSW sits between your application and the network, catching API calls before they leave your app.

Think of MSW like a traffic controller at an airport. Instead of canceling flights (mocking modules) or repainting the planes (changing component code), it intercepts planes mid-flight and redirects them to mock destinations. Your planes (components) don't know the difference—they still use the same runways (fetch, axios, etc.).

Why This Matters

Traditional mocking requires you to either:

  • Mock the entire fetch function globally (vi.mock('fetch'))
  • Mock specific API modules in your codebase
  • Change component code to accept mock dependencies

MSW avoids all of this. Your components use real fetch() calls. Your code stays production-like. MSW intercepts those requests and returns mock responses, making your tests more realistic because they exercise the same code paths as production.

This is especially powerful with React Testing Library's philosophy: test behavior, not implementation. MSW lets you test how your components handle loading states, success responses, and errors—all without mocking React internals.

Key Takeaway: MSW intercepts network requests at the browser/Node level using Service Workers, allowing you to test real fetch/XHR code without changing components or mocking modules directly.