Catch the request inside the Node process and answer it with a prepared ("canned") response. Your real HTTP client code, headers and error handling still run. Only the network call is replaced.
nock sets up interceptors (rules that catch matching requests) per host and path:nock('https://api.example.com').get('/rates').reply(200, { rate: 1.1 })
- Each interceptor matches only once by default.
scope.done()checks that every interceptor was used.nock.disableNetConnect()makes any unexpected real request fail.
Older nock versions don't catch Node's built-in fetch. If you use fetch, check your nock version.
MSW (Mock Service Worker) describes handlers like a small server:http.get('https://api.example.com/rates', () => HttpResponse.json({ rate: 1.1 }))
You start it with setupServer from msw/node. It catches both fetch and the http module. You can share the same handlers between tests and local development.
With either tool, also test the failure cases:
- 500 errors
- timeouts
- broken (malformed) response bodies
- rate limits
- Catch HTTP requests inside the process, so your real client code still runs.
- nock uses per-request interceptors, checks them with scope.done(), and blocks real calls with disableNetConnect().
- MSW uses request handlers, started with setupServer from msw/node.
- Test errors, timeouts and bad payloads, not only success.
- nock (https://github.com/nock/nock)github.com
- MSW docs (https://mswjs.io/docs/)mswjs.io