MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Mocking Network Requests with Mock Service Worker (MSW)0%
Study Materials
React.js for AdvancedProgress 0%
1.1Control Props and Inversion of Control Pattern1.2State Reducer Pattern in Advanced React1.3Prop Getters and Flexible Design Systems1.4Headless UI Architecture and Accessibility Primitives
11.1Integration Testing Multi-Page User Journeys11.2Mocking Network Requests with Mock Service Worker (MSW)11.3End-to-End Testing with Playwright in React11.4Visual Regression and Snapshot Testing Strategies
HomeTutorialsReact.js for AdvancedMocking Network Requests with Mock Service Worker (MSW)
End-to-End Testing with Playwright in React

Mocking Network Requests with Mock Service Worker (MSW)

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Enterprise React applications rely heavily on network APIs. Testing network-dependent components by mocking fetch or axios directly (vi.mock('axios')) leads to brittle tests that couple test assertions to internal implementation libraries. Mock Service Worker (MSW) is the industry standard for network mocking: it intercepts network requests at the network layer using Service Workers (in the browser) and NodeJS network interceptors (in Vitest/Jest).


1. Why MSW Outperforms Naive Mocks

1Traditional Mocking (Brittle):
2Component ──► axios.get() [Mocked via vi.spyOn] ──► Fake Data
3- Breaks if you migrate from Axios to Fetch or TanStack Query!
4 
5MSW Network Mocking (Robust):
6Component ──► axios/fetch ──► HTTP Request ──► [MSW Interceptor catches request] ──► Mock HTTP Response
7- Tests against real HTTP requests, status codes, headers, and payloads!

2. Defining Request Handlers in MSW v2

In MSW v2, handlers use the http namespace:

1// src/mocks/handlers.ts
2import { http, HttpResponse, delay } from "msw";
3 
4export const handlers = [
5 // Mock GET /api/v1/user/profile
6 http.get("https://api.enterprise.com/v1/user/profile", async () => {
7 await delay(50); // Simulate network latency
8 return HttpResponse.json({
9 id: "usr_9981",
10 name: "DevOps Engineer",
11 email: "engineer@enterprise.io",
12 role: "admin",
13 });
14 }),
15 
16 // Mock POST /api/v1/organizations
17 http.post("https://api.enterprise.com/v1/organizations", async ({ request }) => {
18 const payload = (await request.json()) as { name: string };
19 
20 if (!payload.name) {
21 return new HttpResponse(
22 JSON.stringify({ error: "Organization name is required" }),
23 { status: 400, headers: { "Content-Type": "application/json" } }
24 );
25 }
26 
27 return HttpResponse.json(
28 { id: "org_123", name: payload.name, createdAt: new Date().toISOString() },
29 { status: 201 }
30 );
31 }),
32];

3. Configuring MSW in Vitest / Node Test Environment

1// src/mocks/nodeServer.ts
2import { setupServer } from "msw/node";
3import { handlers } from "./handlers";
4 
5export const server = setupServer(...handlers);

Configure your test setup file (vitest.setup.ts) to manage the mock server lifecycle:

1// vitest.setup.ts
2import "@testing-library/jest-dom/vitest";
3import { beforeAll, afterEach, afterAll } from "vitest";
4import { server } from "./src/mocks/nodeServer";
5 
6// Start mock server before running test suite
7beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
8 
9// Reset runtime request handlers between tests to prevent test pollution
10afterEach(() => server.resetHandlers());
11 
12// Clean up and shutdown server when tests finish
13afterAll(() => server.close());

4. Testing Error States and Server Overrides

MSW allows individual tests to override handlers on the fly to simulate server outages, 500 errors, or rate limits:

1// components/UserProfileCard.test.tsx
2import { describe, it, expect } from "vitest";
3import { screen } from "@testing-library/react";
4import { http, HttpResponse } from "msw";
5import { server } from "../mocks/nodeServer";
6import { renderWithProviders } from "../test/test-utils";
7import { UserProfileCard } from "./UserProfileCard";
8 
9describe("UserProfileCard", () => {
10 it("displays user profile information when fetch succeeds", async () => {
11 renderWithProviders(<UserProfileCard />);
12 
13 // Initially displays loading state
14 expect(screen.getByText(/loading profile/i)).toBeInTheDocument();
15 
16 // MSW returns default 200 handler
17 expect(await screen.findByText("DevOps Engineer")).toBeInTheDocument();
18 expect(screen.getByText("engineer@enterprise.io")).toBeInTheDocument();
19 });
20 
21 it("handles 500 server outage gracefully with retry button", async () => {
22 // Override handler for this specific test
23 server.use(
24 http.get("https://api.enterprise.com/v1/user/profile", () => {
25 return new HttpResponse(null, { status: 500 });
26 })
27 );
28 
29 renderWithProviders(<UserProfileCard />);
30 
31 // Assert error state is rendered
32 expect(await screen.findByText(/failed to load profile/i)).toBeInTheDocument();
33 expect(screen.getByRole("button", { name: /retry/i })).toBeInTheDocument();
34 });
35});

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What makes Mock Service Worker (MSW) superior to vi.mock('axios')?
Question 2
In MSW v2, how do you construct a mock JSON response with a 201 Created status?
Question 3
Why is server.resetHandlers() called in afterEach?
Question 4
What does onUnhandledRequest: "error" enforce in MSW setup?
Question 5
Can MSW intercept requests in both NodeJS unit tests and real browser development environments?
Next Lesson

End-to-End Testing with Playwright in React

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Integration Testing Multi-Page User JourneysEnd-to-End Testing with Playwright in React

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext