Nock
HTTP mocking library for Node.js that intercepts outbound requests and returns scripted responses.
Official Documentation ↗v15.0.5. Check the official docs for the latest API surface.Installation
npm install nockpnpm add nockyarn add nockMethods
No methods match this filter.
Overview
Nock intercepts HTTP requests made by Node libraries and returns scripted responses. It lets you test network-dependent code deterministically, without hitting real endpoints.
Core Methods
nock(host) begins a scope; a verb method selects the request and reply defines the response. Options control match counts, persistence, delays and errors, and cleanAll resets state between tests.
Usage Notes
Declare interceptors per test, assert they were consumed, and disable real net connect so unexpected requests fail loudly. Use delays and errors to exercise retry and timeout paths.
Common Pitfalls
Nock hooks the http modules, so undici-based fetch may not be intercepted in newer Node versions. Over-mocking hides integration issues, so keep at least one contract test against a real or recorded server.
Errors
The following points are quoted verbatim from the official documentation. 来源:https://cdn.jsdelivr.net/gh/nock/nock@latest/README.md · 取证方式:HTTP GET 官方 README/文档页(HTML 去标签) · 抓取时间:2026-11-07T13:51:11.940Z. Any error type, throw condition or recovery step not stated there is left unspecified; this page does not infer exception classes or return values.
- It also means that you must setup one interceptor for each request you are going to have, otherwise nock will throw an error because that URL was not present in the interceptor list. (https://cdn.jsdelivr.net/gh/nock/nock@latest/README.md)
- In Nock 10 and earlier, the error was sent in the response body, with a 500 HTTP response status code. (https://cdn.jsdelivr.net/gh/nock/nock@latest/README.md)
FAQ
- Does nock work with fetch or axios?
- Nock patches the Node HTTP and HTTPS modules, so libraries that use them are intercepted. Fetch built on undici may bypass nock, so tests using global fetch may need a different mocking approach.
- How do I assert a request was made?
- Scopes are maintained until cleanAll. If a request does not match any interceptor, nock throws a NoMatchError, and pending interceptors can be inspected with scope.isDone().
- Can I delay or error responses?
- Use .delay(ms) to simulate latency and .replyWithError(error) to simulate network failures, which is useful for timeout and retry testing.
Report a problem with this API docOpens a pre-filled issue on GitHub.