Software Testing & QA (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
Why Mock Service Worker (MSW) is superior to module mocking (Axios/Fetch mocks).
senior LevelCode ExampleSystem DesignHTTP & REST APIs
In Simple Words:
- Module Mocking (
jest.mock('axios')):- Intercepts code inside your application runtime.
- Couples tests to the specific HTTP client implementation. If you refactor from
axiosto nativefetch, all unit tests break!
- MSW (Mock Service Worker):
- Operates at the network protocol layer via Service Workers in the browser and native
node:httpinterceptors in Node. - The application actually makes real HTTP requests; MSW intercepts the network packets transparently. Tests verify genuine network behavior without coupling to HTTP library details.
- Operates at the network protocol layer via Service Workers in the browser and native
typescript
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
export const server = setupServer(
http.get('/api/users/:id', ({ params }) => {
return HttpResponse.json({ id: params.id, name: 'Alice' });
})
);