Guide · Open source
How to use nock: mock HTTP requests in Node.js tests
Updated · written with AI from the project's own documentation and checked against our catalogue data
Nock is a JavaScript library for Node.js that fakes HTTP responses during testing. It overrides Node's built-in HTTP request function, so code that calls external APIs can be tested without contacting those APIs. This guide shows you how to install it, describe the requests you expect, and return the replies your tests need.
Quick start
- 1Install nock. Run npm install --save-dev nock in your Node.js project.
- 2Create a scope. Call nock with the host you want to intercept, such as a string URL, a URL object or a RegExp.
- 3Describe the request. Chain the HTTP verb and path, for example .get('/resource').
- 4Set the reply. Call .reply() with a status code and body the test should receive.
- 5Run the code under test. Call your module as normal in your test so it makes its HTTP request to the mocked host.
- 6Check and clean up. Use .isDone() to confirm the expected request happened, then clean up pending mocks with .cleanAll().
Install nock as a dev dependency
Nock is installed with npm and is only needed while you run tests, so it goes in as a dev dependency. The only prerequisite named in the source is Node.js. The README also notes that the latest nock version supports all currently maintained Node versions, and it lists older nock versions with the Node versions they supported.
$ npm install --save-dev nockSet up an interceptor for a host and path
In your test, create a scope with the host you want to intercept, then chain the HTTP verb, the path and a reply. The README example intercepts every HTTP call to the GitHub API host, matches an HTTPS GET to a license path, and replies with status 200 and a JSON body.
The hostname can be a string, a URL object or a RegExp. You can choose whether or not to include the protocol in the hostname matching.
- The request path can be a string, a RegExp or a filter function.
- Any HTTP verb can be used in the chain.
- Interceptors are removed once they are used, so set up one for each request you expect.
const nock = require('nock')
const scope = nock('https://api.github.com')
.get('/repos/atom/atom/license')
.reply(200, {
license: {
key: 'mit',
name: 'MIT License',
spdx_id: 'MIT',
url: 'https://api.github.com/licenses/mit',
node_id: 'MDc6TGljZW5zZTEz',
},
})Match request bodies
You can pass a second argument to get, post, put or delete to match the request body. The README describes five kinds of argument: a string for an exact match, a Buffer for an exact match, a RegExp tested against the stringified body, a JSON object with optional RegExp values for its keys, and a function that receives the body and returns true for a match.
- String: exact match on the stringified body.
- Buffer: exact match on the stringified body.
- RegExp: tested against the stringified body.
- JSON object: exact match, with RegExp allowed as key values.
- Function: receives the body object and returns true if it should match.
- For partial matching of complex nested bodies, the README points to libraries such as lodash.matches.
nock('http://www.example.com')
.post('/login', { username: 'pgte', password: /.+/i })
.reply(200, { id: '123ABC' })Control how interceptors are reused
Because each interceptor is removed after it is used, you can intercept two or more calls to the same URL and return different responses on each one. If you want an interceptor to stay active for repeated calls, the README documents the .persist() method for that purpose.
- Use one interceptor per expected request, or nock will throw an error for an unmatched URL.
- Use .persist() to keep an interceptor from being removed after use.
Simulate errors and delays
Nock lets you control failure cases in a predictable way. The README has sections on replying with errors, delaying the connection, delaying the response body, and repeating a response a set number of times. Use these to check how your code handles timeouts, failures and slow services without depending on a real server.
- Replying with errors is covered in the README under its own section.
- Delays can be applied to the connection or to the response body.
- A response can be repeated n times.
Clean up between tests
The README's Expectations section documents methods such as .isDone() for checking whether an interceptor was used, and .cleanAll() for removing interceptors. Calling cleanup between tests keeps one test's mocks from leaking into the next. The Restoring section covers putting Node's HTTP behaviour back to normal.
- .isDone() checks whether the expected requests happened.
- .cleanAll() removes pending interceptors.
- .pendingMocks() and .activeMocks() list what is still outstanding.
What people use it for
- Testing a module that calls a third-party API, such as the GitHub API example in the README, without contacting it.
- Testing how your code handles an error status or a failed request by replying with errors.
- Checking timeout handling by adding a delay to the connection or response body.
- Testing code that makes several calls to the same URL and needs a different reply for each call.
Frequently asked questions
How do I install nock?
Run npm install --save-dev nock in your project. The README lists this as the install command and says nock is added as a dev dependency.
What do I need to run nock?
The source names Node.js as the prerequisite. The README describes nock specifically for Node.js, so it is not meant for projects running on other platforms.
Is nock free to use?
Nock is released under the MIT licence, as stated in the project's details.
How does nock work?
Nock overrides Node's http.request function, and it also overrides http.ClientRequest to cover modules that use it directly. This is how it fakes responses without contacting the real server.
What are alternatives to nock?
The comparable projects listed are msw, axios-mock-adapter and polly-js. Pick one based on whether you mock at the network level, at the Axios level, or record and replay requests.
Why does my nock test fail with an unmatched request?
Interceptors are removed after they are used, so each expected request needs its own interceptor. Add one for each call, or use .persist() if the same interceptor should stay active.
New agent skills, repos and AI tools — every week
The best new skills and open-source projects, the fastest-growing repos, and one free prompt. Five minutes to read. Unsubscribe anytime.
Our verdict
Nock suits Node.js developers who want their automated tests isolated from external APIs and need to simulate errors or delays in a controlled way. It is not suitable for non-developers, for projects that do not run on Node.js, or for anyone who needs to test against a real live server.
Install options & downloads