Interview frequency: …
Short answer
MSW intercepts requests at the Network Layer with a Service Worker or Node.js interceptors without changing the application's original fetch calls.
Explanation
Instead of using jest.spyOn(global, "fetch"), manually mocking Response objects, and altering application code, MSW lets you define realistic request handlers that accurately simulate the server. The same mocks can be used in Jest tests, local browser development, and E2E tests without duplicated code.
Code example
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
export const server = setupServer(
http.get('/api/user', () => {
return HttpResponse.json({ id: '1', name: 'Ahmed' });
})
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());Common mistakes
- Forgetting to call server.resetHandlers() after each test, leaking custom error handlers into later tests.