{"_attachments":{},"_id":"nock","_rev":"116184-61f18f600053da989103ec5a","author":{"name":"Pedro Teixeira","email":"pedro.teixeira@gmail.com"},"description":"HTTP server mocking and expectations library for Node.js","dist-tags":{"beta":"14.0.0-beta.5","latest":"13.5.4","next":"13.0.0","release-11.x":"11.9.1"},"license":"MIT","maintainers":[{"name":"gr2m","email":"gregor@martynus.net"},{"name":"pgte","email":"i@pgte.me"},{"name":"paulmelnikow","email":"npm@zephyr.to"},{"name":"nockbot","email":"nockbot@martynus.net"}],"name":"nock","readme":"# Nock\n\n[![npm](https://img.shields.io/npm/v/nock.svg)][npmjs]\n[![Build Status](https://travis-ci.org/nock/nock.svg)][build]\n![Coverage Status](http://img.shields.io/badge/coverage-100%25-brightgreen.svg)\n[![Backers on Open Collective](https://opencollective.com/nock/backers/badge.svg)](#backers)\n[![Sponsors on Open Collective](https://opencollective.com/nock/sponsors/badge.svg)](#sponsors)\n\n[npmjs]: https://www.npmjs.com/package/nock\n[build]: https://travis-ci.org/nock/nock\n\n> **Notice**\n>\n> We have introduced experimental support for fetch. Please share your feedback with us. You can install it by:\n>\n> ```\n> npm install --save-dev nock@beta\n> ```\n\nHTTP server mocking and expectations library for Node.js\n\nNock can be used to test modules that perform HTTP requests in isolation.\n\nFor instance, if a module performs HTTP requests to a CouchDB server or makes HTTP requests to the Amazon API, you can test that module in isolation.\n\n**Table of Contents**\n\n\n\n- [How does it work?](#how-does-it-work)\n- [Install](#install)\n - [Node version support](#node-version-support)\n- [Usage](#usage)\n - [READ THIS! - About interceptors](#read-this---about-interceptors)\n - [Specifying hostname](#specifying-hostname)\n - [Specifying path](#specifying-path)\n - [Specifying request body](#specifying-request-body)\n - [Specifying request query string](#specifying-request-query-string)\n - [Specifying replies](#specifying-replies)\n - [Access original request and headers](#access-original-request-and-headers)\n - [Replying with errors](#replying-with-errors)\n - [Specifying headers](#specifying-headers)\n - [Header field names are case-insensitive](#header-field-names-are-case-insensitive)\n - [Specifying Request Headers](#specifying-request-headers)\n - [Specifying Reply Headers](#specifying-reply-headers)\n - [Default Reply Headers](#default-reply-headers)\n - [Including Content-Length Header Automatically](#including-content-length-header-automatically)\n - [Including Date Header Automatically](#including-date-header-automatically)\n - [HTTP Verbs](#http-verbs)\n - [Support for HTTP and HTTPS](#support-for-http-and-https)\n - [Non-standard ports](#non-standard-ports)\n - [Repeat response n times](#repeat-response-n-times)\n - [Delay the response](#delay-the-response)\n - [Delay the connection](#delay-the-connection)\n - [Technical Details](#technical-details)\n - [Delay the response body](#delay-the-response-body)\n - [Technical Details](#technical-details-1)\n - [Chaining](#chaining)\n - [Scope filtering](#scope-filtering)\n - [Conditional scope filtering](#conditional-scope-filtering)\n - [Path filtering](#path-filtering)\n - [Request Body filtering](#request-body-filtering)\n - [Request Headers Matching](#request-headers-matching)\n - [Optional Requests](#optional-requests)\n - [Allow **unmocked** requests on a mocked hostname](#allow-unmocked-requests-on-a-mocked-hostname)\n- [Expectations](#expectations)\n - [.isDone()](#isdone)\n - [.cleanAll()](#cleanall)\n - [.abortPendingRequests()](#abortpendingrequests)\n - [.persist()](#persist)\n - [.pendingMocks()](#pendingmocks)\n - [.activeMocks()](#activemocks)\n - [.isActive()](#isactive)\n - [.clone()](#clone)\n- [Restoring](#restoring)\n- [Activating](#activating)\n- [Turning Nock Off (experimental!)](#turning-nock-off-experimental)\n- [Enable/Disable real HTTP requests](#enabledisable-real-http-requests)\n - [Disabling requests](#disabling-requests)\n - [Enabling requests](#enabling-requests)\n - [Resetting NetConnect](#resetting-netconnect)\n- [Recording](#recording)\n - [`dont_print` option](#dont_print-option)\n - [`output_objects` option](#output_objects-option)\n - [`enable_reqheaders_recording` option](#enable_reqheaders_recording-option)\n - [`logging` option](#logging-option)\n - [`use_separator` option](#use_separator-option)\n - [.removeInterceptor()](#removeinterceptor)\n- [Events](#events)\n - [Global no match event](#global-no-match-event)\n- [Nock Back](#nock-back)\n - [Setup](#setup)\n - [Options](#options)\n - [Usage](#usage-1)\n - [Options](#options-1)\n - [Example](#example)\n - [Modes](#modes)\n - [Verifying recorded fixtures](#verifying-recorded-fixtures)\n - [Example](#example-1)\n- [Common issues](#common-issues)\n - [Axios](#axios)\n - [Memory issues with Jest](#memory-issues-with-jest)\n- [Debugging](#debugging)\n- [Contributing](#contributing)\n- [Contributors](#contributors)\n- [Sponsors](#sponsors)\n- [License](#license)\n\n\n\n## How does it work?\n\nNock works by overriding Node's `http.request` function. Also, it overrides `http.ClientRequest` too to cover for modules that use it directly.\n\n## Install\n\n```sh\n$ npm install --save-dev nock\n```\n\n### Node version support\n\nThe latest version of nock supports all currently maintained Node versions, see [Node Release Schedule](https://github.com/nodejs/Release#release-schedule)\n\nHere is a list of past nock versions with respective node version support\n\n| node | nock |\n| ---- | ---------- |\n| 0.10 | up to 8.x |\n| 0.11 | up to 8.x |\n| 0.12 | up to 8.x |\n| 4 | up to 9.x |\n| 5 | up to 8.x |\n| 6 | up to 10.x |\n| 7 | up to 9.x |\n| 8 | up to 11.x |\n| 9 | up to 9.x |\n\n## Usage\n\nOn your test, you can setup your mocking object like this:\n\n```js\nconst nock = require('nock')\n\nconst scope = nock('https://api.github.com')\n .get('/repos/atom/atom/license')\n .reply(200, {\n license: {\n key: 'mit',\n name: 'MIT License',\n spdx_id: 'MIT',\n url: 'https://api.github.com/licenses/mit',\n node_id: 'MDc6TGljZW5zZTEz',\n },\n })\n```\n\nThis setup says that we will intercept every HTTP call to `https://api.github.com`.\n\nIt will intercept an HTTPS GET request to `/repos/atom/atom/license`, reply with\na status 200, and the body will contain a (partial) response in JSON.\n\n### READ THIS! - About interceptors\n\nWhen you setup an interceptor for a URL and that interceptor is used, it is removed from the interceptor list.\nThis means that you can intercept 2 or more calls to the same URL and return different things on each of them.\nIt 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.\nIf you donβt want interceptors to be removed as they are used, you can use the [.persist()](#persist) method.\n\n### Specifying hostname\n\nThe request hostname can be a string, URL, or a RegExp.\n\n```js\nconst scope = nock('http://www.example.com')\n .get('/resource')\n .reply(200, 'domain matched')\n```\n\n```js\nconst scope = nock(new URL('http://www.example.com'))\n .get('/resource')\n .reply(200, 'domain matched')\n```\n\n```js\nconst scope = nock(/example\\.com/)\n .get('/resource')\n .reply(200, 'domain regex matched')\n```\n\n> Note: You can choose to include or not the protocol in the hostname matching.\n\n### Specifying path\n\nThe request path can be a string, a RegExp or a filter function and you can use any [HTTP verb](#http-verbs).\n\nUsing a string:\n\n```js\nconst scope = nock('http://www.example.com')\n .get('/resource')\n .reply(200, 'path matched')\n```\n\nUsing a regular expression:\n\n```js\nconst scope = nock('http://www.example.com')\n .get(/source$/)\n .reply(200, 'path using regex matched')\n```\n\nUsing a function:\n\n```js\nconst scope = nock('http://www.example.com')\n .get(uri => uri.includes('cats'))\n .reply(200, 'path using function matched')\n```\n\n### Specifying request body\n\nYou can specify the request body to be matched as the second argument to the `get`, `post`, `put` or `delete` specifications. There are five types of second argument allowed:\n\n**String**: nock will exact match the stringified request body with the provided string\n\n```js\nnock('http://www.example.com')\n .post('/login', 'username=pgte&password=123456')\n .reply(200, { id: '123ABC' })\n```\n\n**Buffer**: nock will exact match the stringified request body with the provided buffer\n\n```js\nnock('http://www.example.com')\n .post('/login', Buffer.from([0xff, 0x11]))\n .reply(200, { id: '123ABC' })\n```\n\n**RegExp**: nock will test the stringified request body against the provided RegExp\n\n```js\nnock('http://www.example.com')\n .post('/login', /username=\\w+/gi)\n .reply(200, { id: '123ABC' })\n```\n\n**JSON object**: nock will exact match the request body with the provided object. In order to increase flexibility, nock also supports RegExp as an attribute value for the keys:\n\n```js\nnock('http://www.example.com')\n .post('/login', { username: 'pgte', password: /.+/i })\n .reply(200, { id: '123ABC' })\n```\n\n**Function**: nock will evaluate the function providing the request body object as first argument. Return true if it should be considered a match:\n\n```js\nnock('http://www.example.com')\n .post('/login', body => body.username && body.password)\n .reply(200, { id: '123ABC' })\n```\n\nIn case you need to perform a partial matching on a complex, nested request body you should have a look at libraries like [lodash.matches](https://lodash.com/docs/#matches). Indeed, partial matching can be achieved as:\n\n```js\nnock('http://www.example.com')\n .post('/user', _.matches({ address: { country: 'US' } }))\n .reply(200, { id: '123ABC' })\n```\n\n### Specifying request query string\n\nNock understands query strings. Search parameters can be included as part of the path:\n\n```js\nnock('http://example.com').get('/users?foo=bar').reply(200)\n```\n\nInstead of placing the entire URL, you can specify the query part as an object:\n\n```js\nnock('http://example.com')\n .get('/users')\n .query({ name: 'pedro', surname: 'teixeira' })\n .reply(200, { results: [{ id: 'pgte' }] })\n```\n\nNock supports array-style/object-style query parameters. The encoding format matches with request module.\n\n```js\nnock('http://example.com')\n .get('/users')\n .query({\n names: ['alice', 'bob'],\n tags: {\n alice: ['admin', 'tester'],\n bob: ['tester'],\n },\n })\n .reply(200, { results: [{ id: 'pgte' }] })\n```\n\nA `URLSearchParams` instance can be provided.\n\n```js\nconst params = new URLSearchParams({ foo: 'bar' })\n\nnock('http://example.com').get('/').query(params).reply(200)\n```\n\nNock supports passing a function to query. The function determines if the actual query matches or not.\n\n```js\nnock('http://example.com')\n .get('/users')\n .query(actualQueryObject => {\n // do some compare with the actual Query Object\n // return true for matched\n // return false for not matched\n return true\n })\n .reply(200, { results: [{ id: 'pgte' }] })\n```\n\nTo mock the entire url regardless of the passed query string:\n\n```js\nnock('http://example.com')\n .get('/users')\n .query(true)\n .reply(200, { results: [{ id: 'pgte' }] })\n```\n\nA query string that is already [URL encoded](https://en.wikipedia.org/wiki/Percent-encoding) can be\nmatched by passing the `encodedQueryParams` flag in the options when creating the Scope.\n\n```js\nnock('http://example.com', { encodedQueryParams: true })\n .get('/users')\n .query('foo%5Bbar%5D%3Dhello%20world%21')\n .reply(200, { results: [{ id: 'pgte' }] })\n```\n\n### Specifying replies\n\nYou can specify the return status code for a path on the first argument of reply like this:\n\n```js\nconst scope = nock('http://myapp.iriscouch.com').get('/users/1').reply(404)\n```\n\nYou can also specify the reply body as a string:\n\n```js\nconst scope = nock('http://www.google.com')\n .get('/')\n .reply(200, 'Hello from Google!')\n```\n\nor as a JSON-encoded object:\n\n```js\nconst scope = nock('http://myapp.iriscouch.com').get('/').reply(200, {\n username: 'pgte',\n email: 'pedro.teixeira@gmail.com',\n _id: '4324243fsd',\n})\n```\n\nor even as a file:\n\n```js\nconst scope = nock('http://myapp.iriscouch.com')\n .get('/')\n .replyWithFile(200, __dirname + '/replies/user.json', {\n 'Content-Type': 'application/json',\n })\n```\n\nInstead of an object or a buffer you can also pass in a callback to be evaluated for the value of the response body:\n\n```js\nconst scope = nock('http://www.google.com')\n .post('/echo')\n .reply(201, (uri, requestBody) => requestBody)\n```\n\nIn Nock 11.x it was possible to invoke `.reply()` with a status code and a\nfunction that returns an array containing a status code and body. (The status\ncode from the array would take precedence over the one passed directly to\nreply.) This is no longer allowed. In Nock 12 and later, either call `.reply()` with a\nstatus code and a function that returns the body, or call it with a single\nargument: a function that returns an array containing both the status code and\nbody.\n\nAn asynchronous function that gets an error-first callback as its last argument also works:\n\n```js\nconst scope = nock('http://www.google.com')\n .post('/echo')\n .reply(201, (uri, requestBody, cb) => {\n fs.readFile('cat-poems.txt', cb) // Error-first callback\n })\n```\n\nIn Nock 11 and later, if an error is passed to the callback, Nock will rethrow it as a programmer error.\nIn Nock 10 and earlier, the error was sent in the response body, with a 500 HTTP response status code.\n\nYou can also return the status code and body using just one function:\n\n```js\nconst scope = nock('http://www.google.com')\n .post('/echo')\n .reply((uri, requestBody) => {\n return [\n 201,\n 'THIS IS THE REPLY BODY',\n { header: 'value' }, // optional headers\n ]\n })\n```\n\nor, use an error-first callback that also gets the status code:\n\n```js\nconst scope = nock('http://www.google.com')\n .post('/echo')\n .reply((uri, requestBody, cb) => {\n setTimeout(() => cb(null, [201, 'THIS IS THE REPLY BODY']), 1000)\n })\n```\n\nA Stream works too:\n\n```js\nconst scope = nock('http://www.google.com')\n .get('/cat-poems')\n .reply(200, (uri, requestBody) => {\n return fs.createReadStream('cat-poems.txt')\n })\n```\n\n#### Access original request and headers\n\nIf you're using the reply callback style, you can access the original client request using `this.req` like this:\n\n```js\nconst scope = nock('http://www.google.com')\n .get('/cat-poems')\n .reply(function (uri, requestBody) {\n console.log('path:', this.req.path)\n console.log('headers:', this.req.headers)\n // ...\n })\n```\n\n> Note: Remember to use normal `function` in that case, as arrow functions are using enclosing scope for `this` binding.\n\n#### Replying with errors\n\nYou can reply with an error like this:\n\n```js\nnock('http://www.google.com')\n .get('/cat-poems')\n .replyWithError('something awful happened')\n```\n\nJSON error responses are allowed too:\n\n```js\nnock('http://www.google.com').get('/cat-poems').replyWithError({\n message: 'something awful happened',\n code: 'AWFUL_ERROR',\n})\n```\n\n> Note: This will emit an `error` event on the `request` object, not the reply.\n\n### Specifying headers\n\n#### Header field names are case-insensitive\n\nPer [HTTP/1.1 4.2 Message Headers](http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2) specification, all message headers are case insensitive and thus internally Nock uses lower-case for all field names even if some other combination of cases was specified either in mocking specification or in mocked requests themselves.\n\n#### Specifying Request Headers\n\nYou can specify the request headers like this:\n\n```js\nconst scope = nock('http://www.example.com', {\n reqheaders: {\n authorization: 'Basic Auth',\n },\n})\n .get('/')\n .reply(200)\n```\n\nOr you can use a regular expression or function to check the header values. The\nfunction will be passed the header value.\n\n```js\nconst scope = nock('http://www.example.com', {\n reqheaders: {\n 'X-My-Headers': headerValue => headerValue.includes('cats'),\n 'X-My-Awesome-Header': /Awesome/i,\n },\n})\n .get('/')\n .reply(200)\n```\n\nIf `reqheaders` is not specified or if `host` is not part of it, Nock will automatically add `host` value to request header.\n\nIf no request headers are specified for mocking then Nock will automatically skip matching of request headers. Since the `host` header is a special case which may get automatically inserted by Nock, its matching is skipped unless it was _also_ specified in the request being mocked.\n\nYou can also have Nock fail the request if certain headers are present:\n\n```js\nconst scope = nock('http://www.example.com', {\n badheaders: ['cookie', 'x-forwarded-for'],\n})\n .get('/')\n .reply(200)\n```\n\nWhen invoked with this option, Nock will not match the request if any of the `badheaders` are present.\n\nBasic authentication can be specified as follows:\n\n```js\nconst scope = nock('http://www.example.com')\n .get('/')\n .basicAuth({ user: 'john', pass: 'doe' })\n .reply(200)\n```\n\n#### Specifying Reply Headers\n\nYou can specify the reply headers like this:\n\n```js\nconst scope = nock('https://api.github.com')\n .get('/repos/atom/atom/license')\n .reply(200, { license: 'MIT' }, { 'X-RateLimit-Remaining': 4999 })\n```\n\nOr you can use a function to generate the headers values. The function will be\npassed the request, response, and response body (if available). The body will\nbe either a buffer, a stream, or undefined.\n\n```js\nconst scope = nock('http://www.headdy.com')\n .get('/')\n .reply(200, 'Hello World!', {\n 'Content-Length': (req, res, body) => body.length,\n ETag: () => `${Date.now()}`,\n })\n```\n\n#### Default Reply Headers\n\nYou can also specify default reply headers for all responses like this:\n\n```js\nconst scope = nock('http://www.headdy.com')\n .defaultReplyHeaders({\n 'X-Powered-By': 'Rails',\n 'Content-Type': 'application/json',\n })\n .get('/')\n .reply(200, 'The default headers should come too')\n```\n\nOr you can use a function to generate the default headers values:\n\n```js\nconst scope = nock('http://www.headdy.com')\n .defaultReplyHeaders({\n 'Content-Length': (req, res, body) => body.length,\n })\n .get('/')\n .reply(200, 'The default headers should come too')\n```\n\n#### Including Content-Length Header Automatically\n\nWhen using `interceptor.reply()` to set a response body manually, you can have the\n`Content-Length` header calculated automatically.\n\n```js\nconst scope = nock('http://www.headdy.com')\n .replyContentLength()\n .get('/')\n .reply(200, { hello: 'world' })\n```\n\n**NOTE:** this does not work with streams or other advanced means of specifying\nthe reply body.\n\n#### Including Date Header Automatically\n\nYou can automatically append a `Date` header to your mock reply:\n\n```js\nconst scope = nock('http://www.headdy.com')\n .replyDate()\n .get('/')\n .reply(200, { hello: 'world' })\n```\n\nOr provide your own `Date` object:\n\n```js\nconst scope = nock('http://www.headdy.com')\n .replyDate(new Date(2015, 0, 1))\n .get('/')\n .reply(200, { hello: 'world' })\n```\n\n### HTTP Verbs\n\nNock supports any HTTP verb, and it has convenience methods for the GET, POST, PUT, HEAD, DELETE, PATCH, OPTIONS and MERGE HTTP verbs.\n\nYou can intercept any HTTP verb using `.intercept(path, verb [, requestBody [, options]])`:\n\n```js\nconst scope = nock('http://my.domain.com')\n .intercept('/path', 'PATCH')\n .reply(304)\n```\n\n### Support for HTTP and HTTPS\n\nBy default nock assumes HTTP. If you need to use HTTPS you can specify the `https://` prefix like this:\n\n```js\nconst scope = nock('https://secure.my.server.com')\n// ...\n```\n\n### Non-standard ports\n\nYou are able to specify a non-standard port like this:\n\n```js\nconst scope = nock('http://my.server.com:8081')\n```\n\n### Repeat response n times\n\nYou are able to specify the number of times to repeat the same response.\n\n**NOTE:** When request times is more than the number you specified, you will get an error before cleaning this interceptor.\n\n```js\nnock('http://zombo.com').get('/').times(4).reply(200, 'Ok')\n\nhttp.get('http://zombo.com/') // respond body \"Ok\"\nhttp.get('http://zombo.com/') // respond body \"Ok\"\nhttp.get('http://zombo.com/') // respond body \"Ok\"\nhttp.get('http://zombo.com/') // respond body \"Ok\"\n\n// This code will get an error with message:\n// Nock: No match for request\nhttp.get('http://zombo.com/')\n\n// clean your interceptor\nnock.cleanAll()\n\nhttp.get('http://zombo.com/') // real respond with zombo.com result\n```\n\nSugar syntax\n\n```js\nnock('http://zombo.com').get('/').once().reply(200, 'Ok')\nnock('http://zombo.com').get('/').twice().reply(200, 'Ok')\nnock('http://zombo.com').get('/').thrice().reply(200, 'Ok')\n```\n\nTo repeat this response for as long as nock is active, use [.persist()](#persist).\n\n### Delay the response\n\nNock can simulate response latency to allow you to test timeouts, race conditions, an other timing related scenarios. \nYou are able to specify the number of milliseconds that your reply should be delayed.\n\n```js\nnock('http://my.server.com')\n .get('/')\n .delay(2000) // 2 seconds delay will be applied to the response header.\n .reply(200, '')\n```\n\n`delay(1000)` is an alias for `delayConnection(1000).delayBody(0)` \n`delay({ head: 1000, body: 2000 })` is an alias for `delayConnection(1000).delayBody(2000)` \nBoth of which are covered in detail below.\n\n#### Delay the connection\n\nYou are able to specify the number of milliseconds that your connection should be idle before it starts to receive the response.\n\nTo simulate a socket timeout, provide a larger value than the timeout setting on the request.\n\n```js\nnock('http://my.server.com')\n .get('/')\n .delayConnection(2000) // 2 seconds\n .reply(200, '')\n\nreq = http.request('http://my.server.com', { timeout: 1000 })\n```\n\nNock emits timeout events almost immediately by comparing the requested connection delay to the timeout parameter passed to `http.request()` or `http.ClientRequest#setTimeout()`. \nThis allows you to test timeouts without using fake timers or slowing down your tests.\nIf the client chooses to _not_ take an action (e.g. abort the request), the request and response will continue on as normal, after real clock time has passed.\n\n##### Technical Details\n\nFollowing the `'finish'` event being emitted by `ClientRequest`, Nock will wait for the next event loop iteration before checking if the request has been aborted.\nAt this point, any connection delay value is compared against any request timeout setting and a [`'timeout'`](https://nodejs.org/api/http.html#http_event_timeout) is emitted when appropriate from the socket and the request objects.\nA Node timeout timer is then registered with any connection delay value to delay real time before checking again if the request has been aborted and the [`'response'`](http://nodejs.org/api/http.html#http_event_response) is emitted by the request.\n\nA similar method, `.socketDelay()` was removed in version 13. It was thought that having two methods so subtlety similar was confusing. \nThe discussion can be found at https://github.com/nock/nock/pull/1974.\n\n#### Delay the response body\n\nYou are able to specify the number of milliseconds that the response body should be delayed. \nThis is the time between the headers being received and the body starting to be received.\n\n```js\nnock('http://my.server.com')\n .get('/')\n .delayBody(2000) // 2 seconds\n .reply(200, '')\n```\n\n##### Technical Details\n\nFollowing the [`'response'`](http://nodejs.org/api/http.html#http_event_response) being emitted by `ClientRequest`,\nNock will register a timeout timer with the body delay value to delay real time before the [IncomingMessage](http://nodejs.org/api/http.html#http_http_incomingmessage) emits its first `'data'` or the `'end'` event.\n\n### Chaining\n\nYou can chain behaviour like this:\n\n```js\nconst scope = nock('http://myapp.iriscouch.com')\n .get('/users/1')\n .reply(404)\n .post('/users', {\n username: 'pgte',\n email: 'pedro.teixeira@gmail.com',\n })\n .reply(201, {\n ok: true,\n id: '123ABC',\n rev: '946B7D1C',\n })\n .get('/users/123ABC')\n .reply(200, {\n _id: '123ABC',\n _rev: '946B7D1C',\n username: 'pgte',\n email: 'pedro.teixeira@gmail.com',\n })\n```\n\n### Scope filtering\n\nYou can filter the scope (protocol, domain or port) of nock through a function. The filtering function is accepted at the `filteringScope` field of the `options` argument.\n\nThis can be useful if you have a node module that randomly changes subdomains to which it sends requests, e.g., the Dropbox node module behaves like this.\n\n```js\nconst scope = nock('https://api.dropbox.com', {\n filteringScope: scope => /^https:\\/\\/api[0-9]*.dropbox.com/.test(scope),\n})\n .get('/1/metadata/auto/Photos?include_deleted=false&list=true')\n .reply(200)\n```\n\n### Conditional scope filtering\n\nYou can also choose to filter out a scope based on your system environment (or any external factor). The filtering function is accepted at the `conditionally` field of the `options` argument.\n\nThis can be useful if you only want certain scopes to apply depending on how your tests are executed.\n\n```js\nconst scope = nock('https://api.myservice.com', {\n conditionally: () => true,\n})\n```\n\n### Path filtering\n\nYou can also filter the URLs based on a function.\n\nThis can be useful, for instance, if you have random or time-dependent data in your URL.\n\nYou can use a regexp for replacement, just like String.prototype.replace:\n\n```js\nconst scope = nock('http://api.myservice.com')\n .filteringPath(/password=[^&]*/g, 'password=XXX')\n .get('/users/1?password=XXX')\n .reply(200, 'user')\n```\n\nOr you can use a function:\n\n```js\nconst scope = nock('http://api.myservice.com')\n .filteringPath(path => '/ABC')\n .get('/ABC')\n .reply(200, 'user')\n```\n\nNote that `scope.filteringPath` is not cumulative: it should only be used once per scope.\n\n### Request Body filtering\n\nYou can also filter the request body based on a function.\n\nThis can be useful, for instance, if you have random or time-dependent data in your request body.\n\nYou can use a regexp for replacement, just like String.prototype.replace:\n\n```js\nconst scope = nock('http://api.myservice.com')\n .filteringRequestBody(/password=[^&]*/g, 'password=XXX')\n .post('/users/1', 'data=ABC&password=XXX')\n .reply(201, 'OK')\n```\n\nOr you can use a function to transform the body:\n\n```js\nconst scope = nock('http://api.myservice.com')\n .filteringRequestBody(body => 'ABC')\n .post('/', 'ABC')\n .reply(201, 'OK')\n```\n\nIf you don't want to match the request body you should omit the `body` argument from the method function:\n\n```js\nconst scope = nock('http://api.myservice.com')\n .post('/some_uri') // no body argument\n .reply(200, 'OK')\n```\n\n### Request Headers Matching\n\nIf you need to match requests only if certain request headers match, you can.\n\n```js\nconst scope = nock('http://api.myservice.com')\n // Interceptors created after here will only match when the header `accept` equals `application/json`.\n .matchHeader('accept', 'application/json')\n .get('/')\n .reply(200, {\n data: 'hello world',\n })\n .get('/')\n // Only this interceptor will match the header value `x-my-action` with `MyFirstAction`\n .matchHeader('x-my-action', 'MyFirstAction')\n .reply(200, {\n data: 'FirstActionResponse',\n })\n .get('/')\n // Only this interceptor will match the header value `x-my-action` with `MySecondAction`\n .matchHeader('x-my-action', 'MySecondAction')\n .reply(200, {\n data: 'SecondActionResponse',\n })\n```\n\nYou can also use a regexp for the header body.\n\n```js\nconst scope = nock('http://api.myservice.com')\n .matchHeader('User-Agent', /Mozilla\\/.*/)\n .get('/')\n .reply(200, {\n data: 'hello world',\n })\n```\n\nYou can also use a function for the header body.\n\n```js\nconst scope = nock('http://api.myservice.com')\n .matchHeader('content-length', val => val >= 1000)\n .get('/')\n .reply(200, {\n data: 'hello world',\n })\n```\n\n### Optional Requests\n\nBy default every mocked request is expected to be made exactly once, and until it is it'll appear in `scope.pendingMocks()`, and `scope.isDone()` will return false (see [expectations](#expectations)). In many cases this is fine, but in some (especially cross-test setup code) it's useful to be able to mock a request that may or may not happen. You can do this with `optionally()`. Optional requests are consumed just like normal ones once matched, but they do not appear in `pendingMocks()`, and `isDone()` will return true for scopes with only optional requests pending.\n\n```js\nconst example = nock('http://example.com')\nexample.pendingMocks() // []\nexample.get('/pathA').reply(200)\nexample.pendingMocks() // [\"GET http://example.com:80/path\"]\n\n// ...After a request to example.com/pathA:\nexample.pendingMocks() // []\n\nexample.get('/pathB').optionally().reply(200)\nexample.pendingMocks() // []\n\n// You can also pass a boolean argument to `optionally()`. This\n// is useful if you want to conditionally make a mocked request\n// optional.\nconst getMock = optional =>\n example.get('/pathC').optionally(optional).reply(200)\n\ngetMock(true)\nexample.pendingMocks() // []\ngetMock(false)\nexample.pendingMocks() // [\"GET http://example.com:80/pathC\"]\n```\n\n### Allow **unmocked** requests on a mocked hostname\n\nIf you need some request on the same host name to be mocked and some others to **really** go through the HTTP stack, you can use the `allowUnmocked` option like this:\n\n```js\nconst scope = nock('http://my.existing.service.com', { allowUnmocked: true })\n .get('/my/url')\n .reply(200, 'OK!')\n\n// GET /my/url => goes through nock\n// GET /other/url => actually makes request to the server\n```\n\n> Note: When applying `{allowUnmocked: true}`, if the request is made to the real server, no interceptor is removed.\n\n## Expectations\n\nEvery time an HTTP request is performed for a scope that is mocked, Nock expects to find a handler for it. If it doesn't, it will throw an error.\n\nCalls to nock() return a scope which you can assert by calling `scope.done()`. This will assert that all specified calls on that scope were performed.\n\nExample:\n\n```js\nconst scope = nock('http://google.com')\n .get('/')\n .reply(200, 'Hello from Google!')\n\n// do some stuff\n\nsetTimeout(() => {\n // Will throw an assertion error if meanwhile a \"GET http://google.com\" was\n // not performed.\n scope.done()\n}, 5000)\n```\n\n### .isDone()\n\nYou can call `isDone()` on a single expectation to determine if the expectation was met:\n\n```js\nconst scope = nock('http://google.com').get('/').reply(200)\n\nscope.isDone() // will return false\n```\n\nIt is also available in the global scope, which will determine if all expectations have been met:\n\n```js\nnock.isDone()\n```\n\n### .cleanAll()\n\nYou can cleanup all the prepared mocks (could be useful to cleanup some state after a failed test) like this:\n\n```js\nnock.cleanAll()\n```\n\n### .abortPendingRequests()\n\nYou can abort all current pending request like this:\n\n```js\nnock.abortPendingRequests()\n```\n\n### .persist()\n\nYou can make all the interceptors for a scope persist by calling `.persist()` on it:\n\n```js\nconst scope = nock('http://example.com')\n .persist()\n .get('/')\n .reply(200, 'Persisting all the way')\n```\n\nNote that while a persisted scope will always intercept the requests, it is considered \"done\" after the first interception.\n\nIf you want to stop persisting an individual persisted mock you can call `persist(false)`:\n\n```js\nconst scope = nock('http://example.com').persist().get('/').reply(200, 'ok')\n\n// Do some tests ...\n\nscope.persist(false)\n```\n\nYou can also use `nock.cleanAll()` which removes all mocks, including persistent mocks.\n\nTo specify an exact number of times that nock should repeat the response, use [.times()](#repeat-response-n-times).\n\n### .pendingMocks()\n\nIf a scope is not done, you can inspect the scope to infer which ones are still pending using the `scope.pendingMocks()` function:\n\n```js\nif (!scope.isDone()) {\n console.error('pending mocks: %j', scope.pendingMocks())\n}\n```\n\nIt is also available in the global scope:\n\n```js\nconsole.error('pending mocks: %j', nock.pendingMocks())\n```\n\n### .activeMocks()\n\nYou can see every mock that is currently active (i.e. might potentially reply to requests) in a scope using `scope.activeMocks()`. A mock is active if it is pending, optional but not yet completed, or persisted. Mocks that have intercepted their requests and are no longer doing anything are the only mocks which won't appear here.\n\nYou probably don't need to use this - it mainly exists as a mechanism to recreate the previous (now-changed) behavior of `pendingMocks()`.\n\n```js\nconsole.error('active mocks: %j', scope.activeMocks())\n```\n\nIt is also available in the global scope:\n\n```js\nconsole.error('active mocks: %j', nock.activeMocks())\n```\n\n### .isActive()\n\nYour tests may sometimes want to deactivate the nock interceptor.\nOnce deactivated, nock needs to be re-activated to work.\nYou can check if nock interceptor is active or not by using `nock.isActive()`.\nSample:\n\n```js\nif (!nock.isActive()) {\n nock.activate()\n}\n```\n\n### .clone()\n\nYou can clone a scope by calling `.clone()` on it:\n\n```js\nconst scope = nock('http://example.test')\n\nconst getScope = scope.get('/').reply(200)\nconst postScope = scope.clone().post('/').reply(200)\n```\n\n## Restoring\n\nYou can restore the HTTP interceptor to the normal unmocked behaviour by calling:\n\n```js\nnock.restore()\n```\n\n**note 1**: restore does not clear the interceptor list. Use [nock.cleanAll()](#cleanall) if you expect the interceptor list to be empty.\n\n**note 2**: restore will also remove the http interceptor itself. You need to run [nock.activate()](#activating) to re-activate the http interceptor. Without re-activation, nock will not intercept any calls.\n\n## Activating\n\nOnly for cases where nock has been deactivated using [nock.restore()](#restoring), you can reactivate the HTTP interceptor to start intercepting HTTP calls using:\n\n```js\nnock.activate()\n```\n\n**note**: To check if nock HTTP interceptor is active or inactive, use [nock.isActive()](#isactive).\n\n## Turning Nock Off (experimental!)\n\nYou can bypass Nock completely by setting the `NOCK_OFF` environment variable to `\"true\"`.\n\nThis way you can have your tests hit the real servers just by switching on this environment variable.\n\n```shell script\n$ NOCK_OFF=true node my_test.js\n```\n\n## Enable/Disable real HTTP requests\n\nBy default, any requests made to a host that is not mocked will be executed normally. If you want to block these requests, nock allows you to do so.\n\n### Disabling requests\n\nFor disabling real http requests.\n\n```js\nnock.disableNetConnect()\n```\n\nSo, if you try to request any host not 'nocked', it will throw a `NetConnectNotAllowedError`.\n\n```js\nnock.disableNetConnect()\nconst req = http.get('http://google.com/')\nreq.on('error', err => {\n console.log(err)\n})\n// The returned `http.ClientRequest` will emit an error event (or throw if you're not listening for it)\n// This code will log a NetConnectNotAllowedError with message:\n// Nock: Disallowed net connect for \"google.com:80\"\n```\n\n### Enabling requests\n\nFor enabling any real HTTP requests (the default behavior):\n\n```js\nnock.enableNetConnect()\n```\n\nYou could allow real HTTP requests for certain host names by providing a string or a regular expression for the hostname, or a function that accepts the hostname and returns true or false:\n\n```js\n// Using a string\nnock.enableNetConnect('amazon.com')\n\n// Or a RegExp\nnock.enableNetConnect(/(amazon|github)\\.com/)\n\n// Or a Function\nnock.enableNetConnect(\n host => host.includes('amazon.com') || host.includes('github.com'),\n)\n\nhttp.get('http://www.amazon.com/')\nhttp.get('http://github.com/')\n\nhttp.get('http://google.com/')\n// This will throw NetConnectNotAllowedError with message:\n// Nock: Disallowed net connect for \"google.com:80\"\n```\n\nA common use case when testing local endpoints would be to disable all but localhost, then add in additional nocks for external requests:\n\n```js\nnock.disableNetConnect()\n// Allow localhost connections so we can test local routes and mock servers.\nnock.enableNetConnect('127.0.0.1')\n```\n\n### Resetting NetConnect\n\nWhen you're done with the test, you probably want to set everything back to normal:\n\n```js\nnock.cleanAll()\nnock.enableNetConnect()\n```\n\n## Recording\n\nThis is a cool feature:\n\nGuessing what the HTTP calls are is a mess, especially if you are introducing nock on your already-coded tests.\n\nFor these cases where you want to mock an existing live system you can record and playback the HTTP calls like this:\n\n```js\nnock.recorder.rec()\n// Some HTTP calls happen and the nock code necessary to mock\n// those calls will be outputted to console\n```\n\nRecording relies on intercepting real requests and responses and then persisting them for later use.\n\nIn order to stop recording you should call `nock.restore()` and recording will stop.\n\n**ATTENTION!:** when recording is enabled, nock does no validation, nor will any mocks be enabled. Please be sure to turn off recording before attempting to use any mocks in your tests.\n\n### `dont_print` option\n\nIf you just want to capture the generated code into a var as an array you can use:\n\n```js\nnock.recorder.rec({\n dont_print: true,\n})\n// ... some HTTP calls\nconst nockCalls = nock.recorder.play()\n```\n\nThe `nockCalls` var will contain an array of strings representing the generated code you need.\n\nCopy and paste that code into your tests, customize at will, and you're done! You can call `nock.recorder.clear()` to remove already recorded calls from the array that `nock.recorder.play()` returns.\n\n(Remember that you should do this one test at a time).\n\n### `output_objects` option\n\nIn case you want to generate the code yourself or use the test data in some other way, you can pass the `output_objects` option to `rec`:\n\n```js\nnock.recorder.rec({\n output_objects: true,\n})\n// ... some HTTP calls\nconst nockCallObjects = nock.recorder.play()\n```\n\nThe returned call objects have the following properties:\n\n- `scope` - the scope of the call including the protocol and non-standard ports (e.g. `'https://github.com:12345'`)\n- `method` - the HTTP verb of the call (e.g. `'GET'`)\n- `path` - the path of the call (e.g. `'/pgte/nock'`)\n- `body` - the body of the call, if any\n- `status` - the HTTP status of the reply (e.g. `200`)\n- `response` - the body of the reply which can be a JSON, string, hex string representing binary buffers or an array of such hex strings (when handling `content-encoded` in reply header)\n- `rawHeaders` - the headers of the reply which are formatted as a flat array containing header name and header value pairs (e.g. `['accept', 'application/json', 'set-cookie', 'my-cookie=value']`)\n- `reqheader` - the headers of the request\n\nIf you save this as a JSON file, you can load them directly through `nock.load(path)`. Then you can post-process them before using them in the tests. For example, to add request body filtering (shown here fixing timestamps to match the ones captured during recording):\n\n```js\nnocks = nock.load(pathToJson)\nnocks.forEach(function (nock) {\n nock.filteringRequestBody = (body, aRecordedBody) => {\n if (typeof body !== 'string' || typeof aRecordedBody !== 'string') {\n return body\n }\n\n const recordedBodyResult = /timestamp:([0-9]+)/.exec(aRecordedBody)\n if (recordedBodyResult) {\n const recordedTimestamp = recordedBodyResult[1]\n return body.replace(\n /(timestamp):([0-9]+)/g,\n function (match, key, value) {\n return key + ':' + recordedTimestamp\n },\n )\n } else {\n return body\n }\n }\n})\n```\n\nAlternatively, if you need to pre-process the captured nock definitions before\nusing them (e.g. to add scope filtering) then you can use `nock.loadDefs(path)`\nand `nock.define(nockDefs)`. Shown here is scope filtering for Dropbox node\nmodule which constantly changes the subdomain to which it sends the requests:\n\n```js\n// Pre-process the nock definitions as scope filtering has to be defined before the nocks are defined (due to its very hacky nature).\nconst nockDefs = nock.loadDefs(pathToJson)\nnockDefs.forEach(def => {\n // Do something with the definition object e.g. scope filtering.\n def.options = {\n ...def.options,\n filteringScope: scope => /^https:\\/\\/api[0-9]*.dropbox.com/.test(scope),\n }\n})\n\n// Load the nocks from pre-processed definitions.\nconst nocks = nock.define(nockDefs)\n```\n\n### `enable_reqheaders_recording` option\n\nRecording request headers by default is deemed more trouble than it's worth as some of them depend on the timestamp or other values that may change after the tests have been recorded thus leading to complex postprocessing of recorded tests. Thus by default the request headers are not recorded.\n\nThe genuine use cases for recording request headers (e.g. checking authorization) can be handled manually or by using `enable_reqheaders_recording` in `recorder.rec()` options.\n\n```js\nnock.recorder.rec({\n dont_print: true,\n output_objects: true,\n enable_reqheaders_recording: true,\n})\n```\n\nNote that even when request headers recording is enabled Nock will never record `user-agent` headers. `user-agent` values change with the version of Node and underlying operating system and are thus useless for matching as all that they can indicate is that the user agent isn't the one that was used to record the tests.\n\n### `logging` option\n\nNock will print using `console.log` by default (assuming that `dont_print` is `false`). If a different function is passed into `logging`, nock will send the log string (or object, when using `output_objects`) to that function. Here's a basic example.\n\n```js\nconst appendLogToFile = content => {\n fs.appendFile('record.txt', content)\n}\nnock.recorder.rec({\n logging: appendLogToFile,\n})\n```\n\n### `use_separator` option\n\nBy default, nock will wrap its output with the separator string `<<<<<<-- cut here -->>>>>>` before and after anything it prints, whether to the console or a custom log function given with the `logging` option.\n\nTo disable this, set `use_separator` to false.\n\n```js\nnock.recorder.rec({\n use_separator: false,\n})\n```\n\n### .removeInterceptor()\n\nThis allows removing a specific interceptor. This can be either an interceptor instance or options for a url. It's useful when there's a list of common interceptors shared between tests, where an individual test requires one of the shared interceptors to behave differently.\n\nExamples:\n\n```js\nnock.removeInterceptor({\n hostname: 'localhost',\n path: '/mockedResource',\n})\n```\n\n```js\nnock.removeInterceptor({\n hostname: 'localhost',\n path: '/login',\n method: 'POST',\n proto: 'https',\n})\n```\n\n```js\nconst interceptor = nock('http://example.org').get('somePath')\nnock.removeInterceptor(interceptor)\n```\n\n**Note** `.reply(...)` method returns Scope, not Interceptor, and so it is not a valid argument for `nock.removeInterceptor`. So if your method chain ends with `.reply` to be used with `nock.removeInterceptor` the chain need to be break in between:\n\n```js\n// this will NOT work\nconst interceptor = nock('http://example.org').get('somePath').reply(200, 'OK')\nnock.removeInterceptor(interceptor)\n// this is how it should be\nconst interceptor = nock('http://example.org').get('somePath')\ninterceptor.reply(200, 'OK')\nnock.removeInterceptor(interceptor)\n```\n\n## Events\n\nA scope emits the following events:\n\n- `emit('request', function(req, interceptor, body))`\n- `emit('replied', function(req, interceptor))`\n\n### Global no match event\n\nYou can also listen for no match events like this:\n\n```js\nnock.emitter.on('no match', req => {})\n```\n\n## Nock Back\n\nFixture recording support and playback.\n\n### Setup\n\nYou must specify a fixture directory before using, for example:\n\nIn your test helper\n\n```js\nconst nockBack = require('nock').back\n\nnockBack.fixtures = '/path/to/fixtures/'\nnockBack.setMode('record')\n```\n\n#### Options\n\n- `nockBack.fixtures` : path to fixture directory\n- `nockBack.setMode()` : the mode to use\n\n### Usage\n\nBy default if the fixture doesn't exist, a `nockBack` will create a new fixture and save the recorded output\nfor you. The next time you run the test, if the fixture exists, it will be loaded in.\n\nThe `this` context of the callback function will have a property `scopes` to access all of the loaded\nnock scopes.\n\n```js\nconst nockBack = require('nock').back\nconst request = require('request')\nnockBack.setMode('record')\n\nnockBack.fixtures = __dirname + '/nockFixtures' //this only needs to be set once in your test helper\n\n// recording of the fixture\nnockBack('zomboFixture.json', nockDone => {\n request.get('http://zombo.com', (err, res, body) => {\n nockDone()\n\n // usage of the created fixture\n nockBack('zomboFixture.json', function (nockDone) {\n http.get('http://zombo.com/').end() // respond body \"Ok\"\n\n this.assertScopesFinished() //throws an exception if all nocks in fixture were not satisfied\n http.get('http://zombo.com/').end() // throws exception because someFixture.json only had one call\n\n nockDone() //never gets here\n })\n })\n})\n```\n\nIf your tests are using promises then use `nockBack` like this:\n\n```js\nreturn nockBack('promisedFixture.json').then(({ nockDone, context }) => {\n // do your tests returning a promise and chain it with\n // `.then(nockDone)`\n})\n```\n\nOr, with async/await:\n\n```js\nconst { nockDone, context } = await nockBack('promisedFixture.json')\n// your test code\nnockDone()\n```\n\n#### Options\n\nAs an optional second parameter you can pass the following options\n\n- `before`: a preprocessing function, gets called before nock.define\n- `after`: a postprocessing function, gets called after nock.define\n- `afterRecord`: a postprocessing function, gets called after recording. Is passed the array of scopes recorded and should return the intact array, a modified version of the array, or if custom formatting is desired, a stringified version of the array to save to the fixture\n- `recorder`: custom options to pass to the recorder\n\n##### Example\n\n```js\nfunction prepareScope(scope) {\n scope.filteringRequestBody = (body, aRecordedBody) => {\n if (typeof body !== 'string' || typeof aRecordedBody !== 'string') {\n return body\n }\n\n const recordedBodyResult = /timestamp:([0-9]+)/.exec(aRecordedBody)\n if (recordedBodyResult) {\n const recordedTimestamp = recordedBodyResult[1]\n return body.replace(\n /(timestamp):([0-9]+)/g,\n (match, key, value) => `${key}:${recordedTimestamp}`,\n )\n } else {\n return body\n }\n }\n}\n\nnockBack('exampleFixture.json', { before: prepareScope }, nockDone => {\n request.get('http://example.com', function (err, res, body) {\n // do your tests\n nockDone()\n })\n})\n```\n\n### Modes\n\nTo set the mode call `nockBack.setMode(mode)` or run the tests with the `NOCK_BACK_MODE` environment variable set before loading nock. If the mode needs to be changed programmatically, the following is valid: `nockBack.setMode(nockBack.currentMode)`\n\n- wild: all requests go out to the internet, don't replay anything, doesn't record anything\n\n- dryrun: The default, use recorded nocks, allow http calls, doesn't record anything, useful for writing new tests\n\n- record: use recorded nocks, record new nocks\n\n- update: remove recorded nocks, record nocks\n\n- lockdown: use recorded nocks, disables all http calls even when not nocked, doesn't record\n\n### Verifying recorded fixtures\n\nAlthough you can certainly open the recorded JSON fixtures to manually verify requests recorded by nockBack - it's sometimes useful to put those expectations in your tests.\n\nThe `context.query` function can be used to return all of the interceptors that were recored in a given fixture.\n\nBy itself, this functions as a negative expectation - you can verify that certain calls do NOT happen in the fixture. Since `assertScopesFinished` can verify there are no _extra_ calls in a fixture - pairing the two methods allows you to verify the exact set of HTTP interactions recorded in the fixture. This is especially useful when re-recording for instance, a service that synchronizes via several HTTP calls to an external API.\n\n**NB**: The list of fixtures is only available when reading. It will only be populated for nocks that are played back from fixtures.\n\n#### Example\n\n```js\nit('#synchronize - synchronize with the external API', async localState => {\n const { nockDone, context } = await back('http-interaction.json')\n\n const syncronizer = new Synchronizer(localState)\n\n sycnronizer.syncronize()\n\n nockDone()\n\n context.assertScopesFinished()\n\n expect(context.query()).toEqual(\n expect.arrayContaining([\n expect.objectContaining({\n method: 'POST',\n path: '/create/thing',\n }),\n expect.objectContaining({\n method: 'POST',\n path: 'create/thing',\n }),\n ]),\n )\n})\n```\n\n## Common issues\n\n**\"No match for response\" when using got with error responses**\n\n[Got][] automatically retries failed requests twice. That means if you have a\ntest which mocks a 4xx or 5xx response, got will immediately reissue it. At\nthat point, the mock will have been consumed and the second request will error\nout with **Nock: No match for request**.\n\nThe same is true for `.replyWithError()`.\n\nAdding `{ retry: 0 }` to the `got` invocations will disable retrying, e.g.:\n\n```js\nawait got('http://example.test/', { retry: 0 })\n```\n\nIf you need to do this in all your tests, you can create a module\n`got_client.js` which exports a custom got instance:\n\n```js\nconst got = require('got')\n\nmodule.exports = got.extend({ retry: 0 })\n```\n\nThis is how it's handled in Nock itself (see [#1523][]).\n\n[got]: https://github.com/sindresorhus/got\n[#1523]: https://github.com/nock/nock/issues/1523\n\n### Axios\n\nTo use Nock with [Axios][], you may need to configure Axios to use the Node\nadapter as in the example below:\n\n```js\nimport axios from 'axios'\nimport nock from 'nock'\nimport test from 'ava' // You can use any test framework.\n\n// If you are using jsdom, axios will default to using the XHR adapter which\n// can't be intercepted by nock. So, configure axios to use the node adapter.\n//\n// References:\n// https://github.com/axios/axios/pull/5277\n\naxios.defaults.adapter = 'http'\n\ntest('can fetch test response', async t => {\n // Set up the mock request.\n const scope = nock('http://localhost')\n .get('/test')\n .reply(200, 'test response')\n\n // Make the request. Note that the hostname must match exactly what is passed\n // to `nock()`. Alternatively you can set `axios.defaults.host = 'http://localhost'`\n // and run `axios.get('/test')`.\n await axios.get('http://localhost/test')\n\n // Assert that the expected request was made.\n scope.done()\n})\n```\n\nFor Nock + Axios + Jest to work, you'll have to also adapt your jest.config.js, like so:\n\n```js\nconst config = {\n moduleNameMapper: {\n // Force CommonJS build for http adapter to be available.\n // via https://github.com/axios/axios/issues/5101#issuecomment-1276572468\n '^axios$': require.resolve('axios'),\n },\n}\n```\n\n[axios]: https://github.com/axios/axios\n\n### Memory issues with Jest\n\nMemory issues can be avoided by calling [`nock.restore()`](#restoring) after each test suite. \nOne of the core principles of [Jest](https://jestjs.io/) is that it runs tests in isolation.\nIt does this by manipulating the modules cache of Node in a way that conflicts with how Nock monkey patches the builtin `http` and `https` modules.\n[Related issue with more details](https://github.com/nock/nock/issues/1817).\n\n## Debugging\n\nNock uses [`debug`](https://github.com/visionmedia/debug), so just run with environmental variable `DEBUG` set to `nock.*`.\n\n```console\nuser@local$ DEBUG=nock.* node my_test.js\n```\n\nEach step in the matching process is logged this way and can be useful when determining why a request was not intercepted by Nock.\n\nFor example the following shows that matching failed because the request had an extra search parameter.\n\n```js\nnock('http://example.com').get('/').query({ foo: 'bar' }).reply()\n\nawait got('http://example.com/?foo=bar&baz=foz')\n```\n\n```console\nuser@local$ DEBUG=nock.scope:example.com node my_test.js\n...\nnock.scope:example.com Interceptor queries: {\"foo\":\"bar\"} +1ms\nnock.scope:example.com Request queries: {\"foo\":\"bar\",\"baz\":\"foz\"} +0ms\nnock.scope:example.com query matching failed +0ms\n```\n\n## Contributing\n\nThanks for wanting to contribute! Take a look at our [Contributing Guide](CONTRIBUTING.md) for notes on our commit message conventions and how to run tests.\n\nPlease note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md).\nBy participating in this project you agree to abide by its terms.\n\n## Contributors\n\nThanks goes to these wonderful people ([emoji key](https://github.com/all-contributors/all-contributors#emoji-key)):\n\n\n\n\n
Pedro Teixeira π» π§ | \n n30n0v π» | \n Richard Littauer π§ π» π | \n Ian Walker-Sperber π» | \n Ivan Erceg π» π§ | \n Paul Melnikow π» π§ | \n Gregor Martynus π» π§ πΌ π΅ π | \n
Hutson Betts π΅ | \n Jonas Lilja π΅ π» | \n Benjamin Ki π΅ | \n Chad Fawcett π΅ | \n Laurence Dougal Myers π» | \n SΓ©bastien Van Bruaene π» β οΈ | \n Aras Abbasi π» β οΈ π§ | \n
Saryev Rustam π» β οΈ | \n Michael Solomon π§ π» π | \n