Testing Async UI & API Calls with MSW
Mock HTTP requests with Mock Service Worker to test components that fetch data.
Why Mock Service Worker?
MSW intercepts HTTP requests at the network level using a Service Worker (browser) or http interceptor (Node), letting you mock APIs without touching your application code.
Installing MSW
Install MSW and set up the Node interceptor for Jest/Vitest tests.
// npm install msw --save-dev
// src/mocks/handlers.ts
import { http, HttpResponse } from 'msw';
export const handlers = [
http.get('/api/users', () => {
return HttpResponse.json([{ id: 1, name: 'Alice' }]);
}),
];All lessons in this course
- Integration Testing with React Testing Library
- Testing Async UI & API Calls with MSW
- Getting Started with Playwright for React
- Testing Forms & User Flows End-to-End