NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
npm · #3651 most downloaded on npm
HTTP server mocking and expectations library for Node.js
Last release 13 days ago
21 Sep 2026
Ships fairly regularly
a new release about every 5 weeks
Nearly every release is documented
notes for 60 of the last 60 stable releases
2 versions withdrawn
withdrawn after publishing
15 years old
470 releases · first in 2011
types: data matcher for body and query. (#1725) (59b345c), closes #1724 #1723 /github.com/Microsoft/TypeScript/issues/1897#issuecomment-338650717 #172
Fix crash when matching certain objects (#1714) (fa0a08a), closes #1713
One column per quarter.
types: DataMatcher to allow valid JSON scalars. (#1703) (a700fa2), closes #1702
types: use export = and declares (#1695) (65a8a6a), closes #1694 #1684
Nock 11 includes many under-the-hood improvements, including a fully offline test suite and 100% test coverage. The codebase was also converted to ES6 syntax and formatted with Prettier. Leaning on the test coverage, some substantial refactors have begun.
Many bug fixes are included. See the detailed changelog below or the compare view for details.
http.request signatures added in Node 10.9.conditionally(() => true)afterRecord()
post-processing hook. When afterRecord() returns a string, the
recorder will no longer attempt to re-stringify it. (Added in v11.3).reply() can now be async/promise-returning..reply() or .defaultReplyHeaders(),
can now be done consistently using an object, Map, or flat array.For many developers no code changes will be needed. However, there are several minor changes to the API, and it's possible that you will need to update your code for Nock to keep working properly. It's unlikely that your tests will falsely pass; what's more probable is that your tests will fail until the necessary changes are made.
Nock 11 requires Node 8 or later. Nock supports and tests all the "current" and "maintenance" versions of Node. As of now, that's Node 8, 10, and 12.
In Nock 10, when reply() was invoked with a function, the return values were
handled ambiguously depending on their types.
Consider the following example:
const scope = nock('http://example.com')
.get('/')
.reply(200, () => [500, 'hello world'])
In Nock 10, the 200 was ignored, the 500 was interpreted as the status
code, and the body would contain 'hello world'. This caused problems
when the goal was to return a numeric array, so in Nock 11, the 200 is
properly interpreted as the status code, and [500, 'hello world'] as the
body.
These are the correct calls for Nock 11:
const scope = nock('http://example.com')
.get('/')
.reply(500, 'hello world')
const scope = nock('http://example.com')
.get('/')
.reply(500, () => 'hello world')
The .reply() method can be called with explicit arguments:
.reply() // `statusCode` defaults to `200`.
.reply(statusCode) // `responseBody` defaults to `''`.
.reply(statusCode, responseBody) // `headers` defaults to `{}`.
.reply(statusCode, responseBody, headers)
It can be called with a status code and a function that returns an array:
.reply(statusCode, (path, requestBody) => responseBody)
.reply(statusCode, (path, requestBody) => responseBody, headers)
Alternatively the status code can be included in the array:
.reply((path, requestBody) => [statusCode])
.reply((path, requestBody) => [statusCode, responseBody])
.reply((path, requestBody) => [statusCode, responseBody, headers])
.reply((path, requestBody) => [statusCode, responseBody], headers)
.reply() can also be called with an async or promise-returning function. The
signatures are identical, e.g.
.reply(async (path, requestBody) => [statusCode, responseBody])
.reply(statusCode, async (path, requestBody) => responseBody)
Finally, an error-first callback can be used, e.g.:
.reply((path, requestBody, cb) => cb(undefined, [statusCode, responseBody]))
.reply(statusCode, (path, requestBody, cb) => cb(undefined, responseBody))
In Nock 10, errors in user-provided reply functions were caught by Nock, and generated HTTP responses with status codes of 500. In Nock 11 these errors are not caught, and instead are re-emitted through the request, like any other error that occurs during request processing.
Consider the following example:
const scope = nock('http://example.com')
.post('/echo')
.reply(201, (uri, requestBody, cb) => {
fs.readFile('cat-poems.txt', cb) // Error-first callback
})
When fs.readFile() errors in Nock 10, a 500 error was emitted. To get the
same effect in Nock 11, the example would need to be rewritten to:
const scope = nock('http://example.com')
.post('/echo')
.reply((uri, requestBody, cb) => {
fs.readFile('cat-poems.txt', (err, contents) => {
if (err) {
cb([500, err.stack])
} else {
cb([201, contents])
}
})
})
When .reply() is invoked with something other than a whole number status
code or a function, Nock 11 raises a new error Invalid ... value for status code.
Callback functions provided to the .query method now receive the result of querystring.parse instead of qs.parse.
In particular, querystring.parse does not interpret keys with JSON
path notation:
querystring.parse('foo[bar]=baz') // { "foo[bar]": 'baz' }
qs.parse('foo[bar]=baz') // { foo: { bar: 'baz' } }
In Nock 10, duplicate field names provided to the .query() method were
silently ignored. We decided this was probably hiding unintentionally bugs
and causing frustration with users. In Nock 11, attempts to provide query
params more than once will throw a new error
Query parameters have aleady been defined. This could happen by calling
.query() twice, or by calling .query() after specifying a literal query
string via the path.
nock('http://example.com')
.get('/path')
.query({ foo: 'bar' })
.query({ baz: 'qux' }) // <-- will throw
.reply()
nock('http://example.com')
.get('/path?foo=bar')
.query({ baz: 'qux' }) // <-- will throw
.reply()
Paths in Nock have always required a leading slash. e.g.
const scope = nock('http://example.com')
.get('/path')
.reply()
In Nock 10, if the leading slash was missing the mock would never match. In Nock 11, this raises an error.
The reqheaders parameter should be provided as a plain object, e.g.
nock('http://example.com', { reqheaders: { X-Foo: 'bar' }}). When the
headers are specified incorrectly as e.g. { reqheaders: 1 }, Nock 10 would
behave in unpredictable ways. In Nock 11, a new error
Headers must be provided as an object is thrown.
nock('http://example.com', { reqheaders: 1 })
.get('/')
.reply()
In Nock 10, the ClientRequest instance wrapped the native on method
and aliased once to it. In Nock 11, this been removed and request.once
will correctly call registered listeners...once.
In Nock 10, when the method was not specified in a call to nock.define(),
the method would default to GET. In Nock 11, this raises an error.
In very old versions of nock, recordings may include a response status
code encoded as a string in the reply field. In Nock 10 these strings could
be non-numeric. In Nock 11 this raises an error.
request.end(), including request.end(cb) in Node 12..destroy() method
are propagated correctly. (Added in v11.3).complete property is set when
ending the response.unref() function
(which does nothing).If you discover bugs in this release, please open a bug report on the Nock repo. 🐛
<details>
Interceptor.query twice throws an error.query
method throws an error instead of ignoring subsequent values.conditionally() (#1488) (24e5b47)IncomingMessage.client for parity with real requests (dc71a3b), closes /github.com/nodejs/node/blob/2e613a9c301165d121b19b86e382860323abc22f/lib/_http_incoming.js#L67unref to Socket (#1612) (a75f49f)req.end(cb) compatibility with Node 12 (#1551) (31623fb).matchHeader() with allowUnmocked (#1480) (d6667f0)req.end(cb); prevent TypeError in Node 12 (#1547) (9a494da), closes #1509new ClientMessage() is invoked with no options (#1386) (6d2a312)</details>
add extension to main field in package.json (#1683) (057bbdf), closes #1654
afterRecord support for custom formatting after recording. (#1682) (e0930f8), closes #1599
socket: propagate errors from destroy method (#1675) (de9c40b), closes #1669
types: Add Typescript definitions. (#1676) (2e56fb0), closes #1670
improve error output by showing which URL caused the error
recorder: allow recording req headers when not outputting objects (#1617) (a952d9b), closes /nodejs.org/api/deprecations.html#deprecations_dep0066
Nock 11 includes many under-the-hood improvements, including a fully offline test suite and 100% test coverage. The codebase was also converted to ES6 syntax and formatted with Prettier. Leaning on the test coverage, some substantial refactors have begun.
Many bug fixes are included. See the detailed changelog below or the compare view for details.
http.request signatures added in Node 10.9.conditionally(() => true)afterRecord()
post-processing hook. When afterRecord() returns a string, the
recorder will no longer attempt to re-stringify it. (Added in v11.3).reply() can now be async/promise-returning..reply() or .defaultReplyHeaders(),
can now be done consistently using an object, Map, or flat array.For many developers no code changes will be needed. However, there are several minor changes to the API, and it's possible that you will need to update your code for Nock to keep working properly. It's unlikely that your tests will falsely pass; what's more probable is that your tests will fail until the necessary changes are made.
Nock 11 requires Node 8 or later. Nock supports and tests all the "current" and "maintenance" versions of Node. As of now, that's Node 8, 10, and 12.
In Nock 10, when reply() was invoked with a function, the return values were
handled ambiguously depending on their types.
Consider the following example:
const scope = nock('http://example.com')
.get('/')
.reply(200, () => [500, 'hello world'])
In Nock 10, the 200 was ignored, the 500 was interpreted as the status
code, and the body would contain 'hello world'. This caused problems
when the goal was to return a numeric array, so in Nock 11, the 200 is
properly interpreted as the status code, and [500, 'hello world'] as the
body.
These are the correct calls for Nock 11:
const scope = nock('http://example.com')
.get('/')
.reply(500, 'hello world')
const scope = nock('http://example.com')
.get('/')
.reply(500, () => 'hello world')
The .reply() method can be called with explicit arguments:
.reply() // `statusCode` defaults to `200`.
.reply(statusCode) // `responseBody` defaults to `''`.
.reply(statusCode, responseBody) // `headers` defaults to `{}`.
.reply(statusCode, responseBody, headers)
It can be called with a status code and a function that returns an array:
.reply(statusCode, (path, requestBody) => responseBody)
.reply(statusCode, (path, requestBody) => responseBody, headers)
Alternatively the status code can be included in the array:
.reply((path, requestBody) => [statusCode])
.reply((path, requestBody) => [statusCode, responseBody])
.reply((path, requestBody) => [statusCode, responseBody, headers])
.reply((path, requestBody) => [statusCode, responseBody], headers)
.reply() can also be called with an async or promise-returning function. The
signatures are identical, e.g.
.reply(async (path, requestBody) => [statusCode, responseBody])
.reply(statusCode, async (path, requestBody) => responseBody)
Finally, an error-first callback can be used, e.g.:
.reply((path, requestBody, cb) => cb(undefined, [statusCode, responseBody]))
.reply(statusCode, (path, requestBody, cb) => cb(undefined, responseBody))
In Nock 10, errors in user-provided reply functions were caught by Nock, and generated HTTP rersponses with status codes of 500. In Nock 11 these errors are not caught, and instead are re-emitted through the request, like any other error that occurs during request processing.
Consider the following example:
const scope = nock('http://example.com')
.post('/echo')
.reply(201, (uri, requestBody, cb) => {
fs.readFile('cat-poems.txt', cb) // Error-first callback
})
When fs.readFile() errors in Nock 10, a 500 error was emitted. To get the
same effect in Nock 11, the example would need to be rewritten to:
const scope = nock('http://example.com')
.post('/echo')
.reply((uri, requestBody, cb) => {
fs.readFile('cat-poems.txt', (err, contents) => {
if (err) {
cb([500, err.stack])
} else {
cb([201, contents])
}
})
})
When .reply() is invoked with something other than a whole number status
code or a function, Nock 11 raises a new error Invalid ... value for status code.
Callback functions provided to the .query method now receive the result of
querystring.parse
instead of qs.parse.
In particular, querystring.parse does not interpret keys with JSON
path notation:
querystring.parse('foo[bar]=baz') // { "foo[bar]": 'baz' }
qs.parse('foo[bar]=baz') // { foo: { bar: 'baz' } }
In Nock 10, duplicate field names provided to the .query() method were
silently ignored. We decided this was probably hiding unintentionally bugs
and causing frustration with users. In Nock 11, attempts to provide query
params more than once will throw a new error
Query parameters have aleady been defined. This could happen by calling
.query() twice, or by calling .query() after specifying a literal query
string via the path.
nock('http://example.com')
.get('/path')
.query({ foo: 'bar' })
.query({ baz: 'qux' }) // <-- will throw
.reply()
nock('http://example.com')
.get('/path?foo=bar')
.query({ baz: 'qux' }) // <-- will throw
.reply()
Paths in Nock have always required a leading slash. e.g.
const scope = nock('http://example.com')
.get('/path')
.reply()
In Nock 10, if the leading slash was missing the mock would never match. In Nock 11, this raises an error.
The reqheaders parameter should be provided as a plain object, e.g.
nock('http://example.com', { reqheaders: { X-Foo: 'bar' }}). When the
headers are specified incorrectly as e.g. { reqheaders: 1 }, Nock 10 would
behave in unpredictable ways. In Nock 11, a new error
Headers must be provided as an object is thrown.
nock('http://example.com', { reqheaders: 1 })
.get('/')
.reply()
In Nock 10, the ClientRequest instance wrapped the native on method
and aliased once to it. In Nock 11, this been removed and request.once
will correctly call registered listeners...once.
In Nock 10, when the method was not specified in a call to nock.define(),
the method would default GET. In Nock 11, this raises an error.
In very old versions of nock, recordings may include a response status
code encoded as a string in the reply field. In Nock 10 these strings could
be non-numeric. In Nock 11 this raises an error.
request.end(), including request.end(cb) in Node 12..destroy() method
are propagated correctly. (Added in v11.3).complete property is set when
ending the response.unref() function
(which does nothing).If you discover bugs in this release, please open a bug report on the Nock repo. 🐛
<details>
Interceptor.query twice throws an error.query
method throws an error instead of ignoring subsequent values.conditionally() (#1488) (24e5b47)IncomingMessage.client for parity with real requests (dc71a3b), closes /github.com/nodejs/node/blob/2e613a9c301165d121b19b86e382860323abc22f/lib/_http_incoming.js#L67unref to Socket (#1612) (a75f49f)afterRecord support for custom formatting after recording. (#1682) (e0930f8), closes #1599req.end(cb) compatibility with Node 12 (#1551) (31623fb).matchHeader() with allowUnmocked (#1480) (d6667f0)req.end(cb); prevent TypeError in Node 12 (#1547) (9a494da), closes #1509new ClientMessage() is invoked with no options (#1386) (6d2a312)</details>
Async Reply functions (always emit errors) (#1596) (26fc08f), closes #1596
overhaul body and query matching (#1632) (35221ce), closes #507 #1552
# 11.0.0-beta.29 (2019-07-25) ### Bug Fixes * trigger release
overrider: added support for header modifications before end()
interceptor: duplicate query calls throw (#1630) (2a54482), closes #1626
Interceptor.query twice throws an error.interceptor: duplicate query keys throw (a2208d1), closes #1623
query
method throws an error instead of ignoring subsequent values.allow unmocked when providing literal search params. (#1614) (f8d6cbb), closes #1421
recorder: allow recording req headers when not outputting objects (#1617) (a952d9b), closes /nodejs.org/api/deprecations.html#deprecations_dep0066
added noop method unref to Socket
Support http.request signatures added in Node 10.9+ (#1588) (e3e6a65), closes #1227
request.end accepted arguments (#1591) (ad34222), closes /github.com/nodejs/node/commit/a10bdb51b18dfaad874f3702a1daea51ec2d4514#diff-286202fdbdd74ede
alias connection to socket. (#1590) (659bf01), closes /github.com/nodejs/node/blob/master/lib/_http_client.js#L640-L641 /github.com/nodejs/node/blob/m
Throw error if request headers are not an object
reply: Response headers to more closely match Node's functionality. (#1564) (b687592), closes #1553 /github.com/nodejs/node/blob/908292cf1f551c614a733
Throw an error on invalid truthy reply status codes
requestoverrider: Add method property to mocked requests
Update and clarify how .reply() can be invoked with functions (#1520) (2e779f0), closes /github.com/nock/nock/pull/1517/files#r280139478 #1222
req.end(cb) compatibility with Node 12
Fix req.end(cb); prevent TypeError in Node 12 (#1547) (9a494da), closes #1509
Restore behavior of Interceptor.filteringPath
define: Throw error when legacy reply is in wrong format
# 11.0.0-beta.10 (2019-04-15) ### Features * Add conditionally()
Fix .matchHeader() with allowUnmocked
intercept: Better error message when options is falsy
package: update propagate to version 2.0.0
define: Throw when method is missing
throw error when leading slash is not present in path (#1391) (28b2d43), closes /github.com/nock/nock/pull/1391#discussion_r250725610
intercept: Improve error message when new ClientMessage() is invoked with no options
new ClientMessage() is invoked with no options (#1386) (6d2a312)IncomingMessage.client for parity with real requests (dc71a3b), closes /github.com/nodejs/node/blob/2e613a9c301165d121b19b86e382860323abc22f/lib/_http_incoming.js#L67Mock responses should fire when timers are mocked (#1336) (a213169), closes #1335 #1334
package.engines is supposed to be an object
### BREAKING CHANGES * Drop support for Node 6
Mock responses should fire when timers are mocked (#1335) (cb56669), closes #1334
package.engines shows incorrect versions and is supposed to be an object
## 10.0.4 (2018-12-08) ### Bug Fixes * #1266: throw useful error if "method" parameter is not set for .intercept() – thanks @labsvisual (a90f543), clo
## 10.0.3 (2018-12-03) ### Bug Fixes * filtering by regex
## 10.0.2 (2018-11-03) ### Bug Fixes * #1041: apply filteringPath from nockBack before option (6d5bca2), closes #1041
package: update debug to version 4.1.0 (0c807c9), closes #1214
drop official support for Node < 6
There is no intentional change that breaks usage in Node 4, but as we stop testing in this no longer supported Node version we recommend to no update nock if you still rely on Node 4.
The reason why we decided to go ahead and make a breaking version release is that it became increasingly harder to update dependencies to the latest versions as they also drop support for Node 4.
set socket connecting state to always be false
Allow optionally() to be called with a value, specifying if the mock should be optional
encode an expected buffer the same way when matching as the client
## 9.4.4 (2018-07-31) ### Bug Fixes * #1076: allowUnmocked: true + host regex (#1179) (907be86), closes #1076
## 9.4.3 (2018-07-23) ### Bug Fixes * #1171: When matching the path by function, also check the HTTP method. (9373382), closes #1171
Replaced util._extend with Object.assign due to deprecated since node v6.
request overrider checks req.headers to parse body as JSON
emit 'request' event with body as third parameter
match basePath as regex and path as function
restore compatibility with Node <4.5
use aborted property on http request
# 9.3.0 (2018-05-30) ### Features * support URL objects
Your coding agent can read these notes before it upgrades. Set up the MCP server →