{"_id":"@aleung/nock","_rev":"2-da757707c71ccbce6fc0a1b0d93018a0","name":"@aleung/nock","description":"HTTP Server mocking for Node.js","dist-tags":{"latest":"9.1.51"},"versions":{"9.1.5":{"name":"@aleung/nock","description":"HTTP Server mocking for Node.js","tags":["Mock","HTTP","testing","isolation"],"version":"9.1.5","author":{"name":"Pedro Teixeira","email":"pedro.teixeira@gmail.com"},"contributors":[{"name":"Bin Chang","url":"https://github.com/BinChang"},{"name":"Roman Hotsiy","url":"https://github.com/RomanGotsiy"},{"name":"Jeffrey Jagoda","url":"https://github.com/jagoda"},{"name":"Hidenari Nozaki","url":"https://github.com/ghiden"},{"name":"Ken Sheedlo","url":"https://github.com/ksheedlo"},{"name":"Douglas Eggleton","url":"https://github.com/douglaseggleton"},{"name":"José F. Romaniello","url":"https://github.com/jfromaniello"},{"name":"Benjamin Urban","url":"https://github.com/benurb"},{"name":"Justin","url":"https://github.com/justincy"},{"name":"Brett Porter"},{"name":"Matt Olson"},{"name":"Rémy HUBSCHER"},{"name":"Roly Fentanes"},{"name":"Alexander Simmerl"},{"name":"Pedro Teixeira"},{"name":"Nuno Job"},{"name":"Ian Young"},{"name":"nilsbunger"},{"name":"bacchusrx","email":"bacchusrx@eightstar.ca"},{"name":"Fabiano França"},{"name":"Sascha Drews"},{"name":"Mike Swift"},{"name":"James Herdman"},{"name":"David Björklund"},{"name":"Andrew Kramolisch"},{"name":"Balazs Nagy"},{"name":"Brian J Brennan"},{"name":"Attila Incze"},{"name":"Mac Angell"},{"name":"Tom Hosford"},{"name":"Aurélien Thieriot"},{"name":"Alex Zylman"},{"name":"Celestino Gomes","email":"contact@tinogomes.com"},{"name":"David Rousselie"},{"name":"spenceralger"},{"name":"Ivan Erceg","email":"ivan@softwaremarbles.com","url":"https://github.com/ierceg"},{"name":"Keith Laban","email":"kelaban17@gmail.com","url":"https://github.com/kelaban"},{"name":"Rui Marinho","email":"ruipmarinho@gmail.com","url":"https://github.com/ruimarinho"},{"name":"David Pate","email":"davidtpate@gmail.com","url":"https://github.com/DavidTPate"},{"name":"Matt Oakes","url":"https://github.com/matto1990"},{"name":"Ian Walker-Sperber","url":"https://github.com/ianwsperber"}],"repository":{"type":"git","url":"git+https://github.com/aleung/nock.git"},"bugs":{"url":"http://github.com/aleung/nock/issues"},"engines":["node >= 4.0"],"main":"./index","dependencies":{"chai":">=1.9.2 <4.0.0","debug":"^2.2.0","deep-equal":"^1.0.0","json-stringify-safe":"^5.0.1","lodash":"~4.17.2","mkdirp":"^0.5.0","propagate":"0.4.0","qs":"^6.5.1","semver":"^5.3.0"},"devDependencies":{"async":"^2.1.1","aws-sdk":"^2.0.15","browserify":"^13.0.0","coveralls":"^2.11.2","eslint":"^3.19.0","glob":"^7.1.1","hyperquest":"^1.3.0","isomorphic-fetch":"^2.2.0","istanbul":"^0.4.2","markdown-toc":"^0.13.0","needle":"^1.0.0","node-static":"^0.7.7","nyc":"^10.0.0","request":"2.79.0","request-promise":"^2.0.1","restify":"^4.0.4","restler":"3.4.0","rimraf":"^2.3.2","semver":"^5.3.0","superagent":"^3.5.0","tap":"^10.0.0","zombie":"^5.0.1","semantic-release":"^8.2.0"},"scripts":{"unit":"tap --harmony ./tests/test_*.js","preintegration":"./tests/bin/install_sub_deps versioned","integration":"tap --harmony ./tests/versioned/*/*.tap.js","test":"npm run lint && npm run unit && npm run integration","coverage":"nyc tap --harmony ./tests/test_*.js","coveralls":"cat ./coverage/lcov.info | coveralls","lint":"eslint '**/*.js'","toc":"markdown-toc -i README.md","semantic-release":"semantic-release pre && npm publish && semantic-release post"},"nyc":{"reporter":["lcov","text-summary"],"exclude":["tests/test_*.js"]},"license":"MIT","gitHead":"d7d7d8d2edf723c5d08be4f4e65e66320f4ffb70","homepage":"https://github.com/aleung/nock#readme","_id":"@aleung/nock@9.1.5","_npmVersion":"5.3.0","_nodeVersion":"8.5.0","_npmUser":{"name":"aleung","email":"leoliang@gmail.com"},"dist":{"integrity":"sha512-qsi09cXFO4ewFiqeGz13u+wdhOF/J3D/3a5Fn4xb+VMvte1Qe1RzSNehe9Fm/JQJ2pwyPGX1ZU93GDB1EvTQOw==","shasum":"12fc2259661bf74c74d4ab5fe6e7094ea0e78c6e","tarball":"https://registry.npmjs.org/@aleung/nock/-/nock-9.1.5.tgz","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCwXo0DEuyWBiBTXmG7qzhs9GP/ersJ1V5nPhg8XDGjOQIgR4WEa8f4FN0RitRCwW8rqQ6cKg9GFZHMbQoK2TIy1aI="}]},"maintainers":[{"name":"aleung","email":"leoliang@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/nock-9.1.5.tgz_1513878389274_0.06729689566418529"}},"9.1.51":{"name":"@aleung/nock","description":"HTTP Server mocking for Node.js","tags":["Mock","HTTP","testing","isolation"],"version":"9.1.51","author":{"name":"Pedro Teixeira","email":"pedro.teixeira@gmail.com"},"contributors":[{"name":"Bin Chang","url":"https://github.com/BinChang"},{"name":"Roman Hotsiy","url":"https://github.com/RomanGotsiy"},{"name":"Jeffrey Jagoda","url":"https://github.com/jagoda"},{"name":"Hidenari Nozaki","url":"https://github.com/ghiden"},{"name":"Ken Sheedlo","url":"https://github.com/ksheedlo"},{"name":"Douglas Eggleton","url":"https://github.com/douglaseggleton"},{"name":"José F. Romaniello","url":"https://github.com/jfromaniello"},{"name":"Benjamin Urban","url":"https://github.com/benurb"},{"name":"Justin","url":"https://github.com/justincy"},{"name":"Brett Porter"},{"name":"Matt Olson"},{"name":"Rémy HUBSCHER"},{"name":"Roly Fentanes"},{"name":"Alexander Simmerl"},{"name":"Pedro Teixeira"},{"name":"Nuno Job"},{"name":"Ian Young"},{"name":"nilsbunger"},{"name":"bacchusrx","email":"bacchusrx@eightstar.ca"},{"name":"Fabiano França"},{"name":"Sascha Drews"},{"name":"Mike Swift"},{"name":"James Herdman"},{"name":"David Björklund"},{"name":"Andrew Kramolisch"},{"name":"Balazs Nagy"},{"name":"Brian J Brennan"},{"name":"Attila Incze"},{"name":"Mac Angell"},{"name":"Tom Hosford"},{"name":"Aurélien Thieriot"},{"name":"Alex Zylman"},{"name":"Celestino Gomes","email":"contact@tinogomes.com"},{"name":"David Rousselie"},{"name":"spenceralger"},{"name":"Ivan Erceg","email":"ivan@softwaremarbles.com","url":"https://github.com/ierceg"},{"name":"Keith Laban","email":"kelaban17@gmail.com","url":"https://github.com/kelaban"},{"name":"Rui Marinho","email":"ruipmarinho@gmail.com","url":"https://github.com/ruimarinho"},{"name":"David Pate","email":"davidtpate@gmail.com","url":"https://github.com/DavidTPate"},{"name":"Matt Oakes","url":"https://github.com/matto1990"},{"name":"Ian Walker-Sperber","url":"https://github.com/ianwsperber"}],"repository":{"type":"git","url":"git+https://github.com/aleung/nock.git"},"bugs":{"url":"http://github.com/aleung/nock/issues"},"engines":["node >= 4.0"],"main":"./index","typings":"./index.d.ts","dependencies":{"chai":">=1.9.2 <4.0.0","debug":"^2.2.0","deep-equal":"^1.0.0","json-stringify-safe":"^5.0.1","lodash":"~4.17.2","mkdirp":"^0.5.0","propagate":"0.4.0","qs":"^6.5.1","semver":"^5.3.0"},"devDependencies":{"async":"^2.1.1","aws-sdk":"^2.0.15","browserify":"^13.0.0","coveralls":"^2.11.2","eslint":"^3.19.0","glob":"^7.1.1","hyperquest":"^1.3.0","isomorphic-fetch":"^2.2.0","istanbul":"^0.4.2","markdown-toc":"^0.13.0","needle":"^1.0.0","node-static":"^0.7.7","nyc":"^10.0.0","request":"2.79.0","request-promise":"^2.0.1","restify":"^4.0.4","restler":"3.4.0","rimraf":"^2.3.2","semver":"^5.3.0","superagent":"^3.5.0","tap":"^10.0.0","zombie":"^5.0.1","semantic-release":"^8.2.0"},"scripts":{"unit":"tap --harmony ./tests/test_*.js","preintegration":"./tests/bin/install_sub_deps versioned","integration":"tap --harmony ./tests/versioned/*/*.tap.js","test":"npm run lint && npm run unit && npm run integration","coverage":"nyc tap --harmony ./tests/test_*.js","coveralls":"cat ./coverage/lcov.info | coveralls","lint":"eslint '**/*.js'","toc":"markdown-toc -i README.md","semantic-release":"semantic-release pre && npm publish && semantic-release post"},"nyc":{"reporter":["lcov","text-summary"],"exclude":["tests/test_*.js"]},"license":"MIT","gitHead":"818c2e10d56605a9e07b8e6ab6bf3dd2fabd8170","homepage":"https://github.com/aleung/nock#readme","_id":"@aleung/nock@9.1.51","_npmVersion":"5.5.1","_nodeVersion":"8.9.0","_npmUser":{"name":"aleung","email":"leoliang@gmail.com"},"dist":{"integrity":"sha512-hnUSpMMuy+dOhd045JPefQ5C+Kzb712T0G8WxVdLDsdcv9KdNjfOfSQm/Ni6uJQqLEQOICYDULnuKX5Q2EJIfA==","shasum":"1b819c48ab6f0c12a18e50634a99355d82e7fe66","tarball":"https://registry.npmjs.org/@aleung/nock/-/nock-9.1.51.tgz","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDbCnxUeZRIr5MGFMk40iGQfe41F0gWoGGcY1o5VdgdeQIgONKlQm1EBD1WjS9U1bGHqJfz0LKTp9Q+7pqAS3JtKEQ="}]},"maintainers":[{"name":"aleung","email":"leoliang@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/nock-9.1.51.tgz_1517912729387_0.9408282472286373"}}},"readme":"# Nock\n\n> [![npm version](https://badge.fury.io/js/%40aleung%2Fnock.png)](https://www.npmjs.com/package/@aleung/nock)\n>\n> This is a fork of [node-nock](https://github.com/node-nock/nock).\n>\n> The only difference to original one is that it fixes issue [#754](https://github.com/node-nock/nock/issues/754) -- timeout doesn't work with [request](https://www.npmjs.com/package/request) 2.76.0+. Detail is explained in [PR #859](https://github.com/node-nock/nock/pull/859#issuecomment-290594653). \n>\n> If you don't use nock to test timeout behavior with request 2.76.0+, you should use the original one.\n>\n> I maintain this fork for my own purpose. No guarantee to rebase on origin latest release in time.\n>\n> ```\n> npm install @aleung/nock\n> ```\n>\n\nNock is an HTTP 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<!-- toc -->\n\n- [How does it work?](#how-does-it-work)\n- [Install](#install)\n  * [Node version support](#node-version-support)\n- [Use](#use)\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 body](#delay-the-response-body)\n  * [Delay the response](#delay-the-response)\n  * [Delay the connection](#delay-the-connection)\n  * [Socket timeout](#socket-timeout)\n  * [Chaining](#chaining)\n  * [Scope filtering](#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  * [.persist()](#persist)\n  * [.pendingMocks()](#pendingmocks)\n  * [.activeMocks()](#activemocks)\n  * [.isActive()](#isactive)\n- [Logging](#logging)\n- [Restoring](#restoring)\n- [Activating](#activating)\n- [Turning Nock Off (experimental!)](#turning-nock-off-experimental)\n- [Enable/Disable real HTTP request](#enabledisable-real-http-request)\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)\n    + [Options](#options-1)\n    + [Modes](#modes)\n- [Debugging](#debugging)\n- [PROTIP](#protip)\n- [Contributing](#contributing)\n  * [Generate README TOC](#generate-readme-toc)\n  * [Running tests](#running-tests)\n    + [Airplane mode](#airplane-mode)\n- [License](#license)\n\n<!-- tocstop -->\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 nock\n```\n\n## 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    | 9.x       |\n| 5    | up to 8.x |\n| 6    | 9.x       |\n\n# Use\n\nOn your test, you can setup your mocking object like this:\n\n```js\nvar nock = require('nock');\n\nvar couchdb = nock('http://myapp.iriscouch.com')\n                .get('/users/1')\n                .reply(200, {\n                  _id: '123ABC',\n                  _rev: '946B7D1C',\n                  username: 'pgte',\n                  email: 'pedro.teixeira@gmail.com'\n                 });\n```\n\nThis setup says that we will intercept every HTTP call to `http://myapp.iriscouch.com`.\n\nIt will intercept an HTTP GET request to '/users/1' and reply with a status 200, and the body will contain a user representation in JSON.\n\nThen the test can call the module, and the module will do the HTTP requests.\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 or a RegExp.\n\n```js\nvar scope = nock('http://www.example.com')\n    .get('/resource')\n    .reply(200, 'domain matched');\n```\n\n```js\nvar scope = nock(/example\\.com/)\n    .get('/resource')\n    .reply(200, 'domain regex matched');\n```\n\n> (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\nvar scope = nock('http://www.example.com')\n    .get('/resource')\n    .reply(200, 'path matched');\n```\n\nUsing a regular expression:\n\n```js\nvar scope = nock('http://www.example.com')\n    .get(/source$/)\n    .reply(200, 'path using regex matched');\n```\n\nUsing a function:\n\n```js\nvar scope = nock('http://www.example.com')\n    .get(function(uri) {\n      return uri.indexOf('cats') >= 0;\n    })\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 like this:\n\n```js\nvar scope = nock('http://myapp.iriscouch.com')\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```\n\nThe request body can be a string, a RegExp, a JSON object or a function.\n\n```js\nvar scope = nock('http://myapp.iriscouch.com')\n                .post('/users', /email=.?@gmail.com/gi)\n                .reply(201, {\n                  ok: true,\n                  id: '123ABC',\n                  rev: '946B7D1C'\n                });\n```\n\nIf the request body is a JSON object, a RegExp can be used to match an attribute value.\n\n```js\nvar scope = nock('http://myapp.iriscouch.com')\n                .post('/users', {\n                  username: 'pgte',\n                  password: /a.+/,\n                  email: 'pedro.teixeira@gmail.com'\n                })\n                .reply(201, {\n                  ok: true,\n                  id: '123ABC',\n                  rev: '946B7D1C'\n                });\n```\n\nIf the request body is a function, return true if it should be considered a match:\n\n```js\nvar scope = nock('http://myapp.iriscouch.com')\n                .post('/users', function(body) {\n                  return body.id === '123ABC';\n                })\n                .reply(201, {\n                  ok: true,\n                  id: '123ABC',\n                  rev: '946B7D1C'\n                });\n\n```\n\n## Specifying request query string\n\nNock understands query strings. Instead 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\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(function(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\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\nvar scope = nock('http://myapp.iriscouch.com')\n                .get('/users/1')\n                .reply(404);\n```\n\nYou can also specify the reply body as a string:\n\n```js\nvar 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\nvar scope = nock('http://myapp.iriscouch.com')\n                .get('/')\n                .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\nvar scope = nock('http://myapp.iriscouch.com')\n                .get('/')\n                .replyWithFile(200, __dirname + '/replies/user.json', { 'Content-Type': 'application/json' });\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\nvar scope = nock('http://www.google.com')\n   .filteringRequestBody(/.*/, '*')\n   .post('/echo', '*')\n   .reply(201, function(uri, requestBody) {\n     return requestBody;\n   });\n```\n\nAn asynchronous function that gets an error-first callback as last argument also works:\n\n```js\nvar scope = nock('http://www.google.com')\n   .filteringRequestBody(/.*/, '*')\n   .post('/echo', '*')\n   .reply(201, function(uri, requestBody, cb) {\n     fs.readFile('cat-poems.txt' , cb); // Error-first callback\n   });\n```\n\n> Note: When using a callback, if you call back with an error as first argument, that error will be 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\nvar scope = nock('http://www.google.com')\n   .filteringRequestBody(/.*/, '*')\n   .post('/echo', '*')\n   .reply(function(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\nvar scope = nock('http://www.google.com')\n   .filteringRequestBody(/.*/, '*')\n   .post('/echo', '*')\n   .reply(function(uri, requestBody, cb) {\n     setTimeout(function() {\n       cb(null, [201, 'THIS IS THE REPLY BODY'])\n     }, 1e3);\n   });\n```\n\nA Stream works too:\n```js\nvar scope = nock('http://www.google.com')\n   .get('/cat-poems')\n   .reply(200, function(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\nvar 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### 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')\n  .get('/cat-poems')\n  .replyWithError({'message': 'something awful happened', 'code': 'AWFUL_ERROR'});\n```\n\n> NOTE: This will emit an `error` event on the `request` object, not the reply.\n\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\nvar 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 check the header values. The function will be\npassed the header value.\n\n```js\nvar scope = nock('http://www.example.com', {\n      reqheaders: {\n        'X-My-Headers': function (headerValue) {\n           if (headerValue) {\n             return true;\n           }\n           return false;\n         },\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 `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\nvar 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\nvar scope = nock('http://www.example.com')\n    .get('/')\n    .basicAuth({\n      user: 'john',\n      pass: 'doe'\n    })\n    .reply(200);\n```\n\n### Specifying Reply Headers\n\nYou can specify the reply headers like this:\n\n```js\nvar scope = nock('http://www.headdy.com')\n   .get('/')\n   .reply(200, 'Hello World!', {\n     'X-My-Headers': 'My Header value'\n   });\n```\n\nOr you can use a function to generate the headers values. The function will be\npassed the request, response, and body (if available). The body will be either a\nbuffer, a stream, or undefined.\n\n```js\nvar scope = nock('http://www.headdy.com')\n   .get('/')\n   .reply(200, 'Hello World!', {\n     'X-My-Headers': function (req, res, body) {\n       return body.toString();\n     }\n   });\n```\n\n### Default Reply Headers\n\nYou can also specify default reply headers for all responses like this:\n\n```js\nvar 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\nvar scope = nock('http://www.headdy.com')\n  .defaultReplyHeaders({\n    'Content-Length': function (req, res, body) {\n      return body.length;\n    }\n  })\n  .get('/')\n  .reply(200, 'The default headers should come too');\n```\n\n### Including Content-Length Header Automatically\n\nWhen using `scope.reply()` to set a response body manually, you can have the\n`Content-Length` header calculated automatically.\n\n```js\nvar 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\nvar scope = nock('http://www.headdy.com')\n  .replyDate(new Date(2015, 0, 1)) // defaults to now, must use a Date object\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 and MERGE HTTP verbs.\n\nYou can intercept any HTTP verb using `.intercept(path, verb [, requestBody [, options]])`:\n\n```js\nvar 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\nvar 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\nvar scope = nock('http://my.server.com:8081')\n  ...\n```\n\n## Repeat response n times\n\nYou are able to specify the number of times to repeat the same response.\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\"\nhttp.get('http://zombo.com/'); // 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\n## Delay the response body\nYou are able to specify the number of milliseconds that the response body should be delayed. Response header will be replied immediately.\n`delayBody(1000)` is equivalent to `delay({body: 1000})`.\n\n\n```js\nnock('http://my.server.com')\n  .get('/')\n  .delayBody(2000) // 2 seconds\n  .reply(200, '<html></html>')\n```\n\nNOTE: the [`'response'`](http://nodejs.org/api/http.html#http_event_response) event will occur immediately, but the [IncomingMessage](http://nodejs.org/api/http.html#http_http_incomingmessage) will not emit it's `'end'` event until after the delay.\n\n## Delay the response\n\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, '<html></html>')\n```\n\n`delay()` could also be used as\n\n ```\n delay({\n    head: headDelayInMs,\n    body: bodyDelayInMs\n })\n ```\n\n for example\n\n```js\nnock('http://my.server.com')\n  .get('/')\n  .delay({\n    head: 2000, // header will be delayed for 2 seconds, i.e. the whole response will be delayed for 2 seconds.\n    body: 3000  // body will be delayed for another 3 seconds after header is sent out.\n  })\n  .reply(200, '<html></html>')\n```\n\n## Delay the connection\n\n`delayConnection(1000)` is equivalent to `delay({head: 1000})`.\n\n## Socket timeout\n\nYou are able to specify the number of milliseconds that your connection should be idle, to simulate a socket timeout.\n\n```js\nnock('http://my.server.com')\n  .get('/')\n  .socketDelay(2000) // 2 seconds\n  .reply(200, '<html></html>')\n```\n\nTo test a request like the following:\n\n```js\nreq = http.request('http://my.server.com', function(res) {\n  ...\n});\nreq.setTimeout(1000, function() {\n  req.abort();\n});\nreq.end();\n```\n\nNOTE: the timeout will be fired immediately, and will not leave the simulated connection idle for the specified period of time.\n\n## Chaining\n\nYou can chain behaviour like this:\n\n```js\nvar 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\nvar scope = nock('https://api.dropbox.com', {\n    filteringScope: function(scope) {\n      return /^https:\\/\\/api[0-9]*.dropbox.com/.test(scope);\n    }\n  })\n  .get('/1/metadata/auto/Photos?include_deleted=false&list=true')\n  .reply(200);\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\nvar 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\nvar scope = nock('http://api.myservice.com')\n                .filteringPath(function(path) {\n                   return '/ABC';\n                 })\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\nvar 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\nvar scope = nock('http://api.myservice.com')\n                .filteringRequestBody(function(body) {\n                   return 'ABC';\n                 })\n                .post('/', 'ABC')\n                .reply(201, '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\nvar scope = nock('http://api.myservice.com')\n                .matchHeader('accept', 'application/json')\n                .get('/')\n                .reply(200, {\n                  data: 'hello world'\n                })\n```\n\nYou can also use a regexp for the header body.\n\n```js\nvar 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\nvar scope = nock('http://api.myservice.com')\n                .matchHeader('content-length', function (val) {\n                  return val >= 1000;\n                })\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\nvar 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\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\noptions = {allowUnmocked: true};\nvar scope = nock('http://my.existing.service.com', options)\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> Bear in mind that, 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\nvar google = nock('http://google.com')\n                .get('/')\n                .reply(200, 'Hello from Google!');\n\n// do some stuff\n\nsetTimeout(function() {\n  google.done(); // will throw an assertion error if meanwhile a \"GET http://google.com\" was not performed.\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\nvar scope = nock('http://google.com')\n  .get('/')\n  .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## .persist()\n\nYou can make all the interceptors for a scope persist by calling `.persist()` on it:\n\n```js\nvar scope = nock('http://persisssists.con')\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 a persistent nock you can call `persist(false)`:\n\n```js\nvar scope = nock('http://example.com').persist().get('/').reply(200, 'ok');\n// do some tests ...\nscope.persist(false);\n```\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()) nock.activate()\n```\n\n# Logging\n\nNock can log matches if you pass in a log function like this:\n\n```js\nvar google = nock('http://google.com')\n                .log(console.log)\n                ...\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**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 deactive, use [nock.isActive()](#isactive).\n\n# Turning Nock Off (experimental!)\n\nYou can bypass Nock completely by setting `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```js\n$ NOCK_OFF=true node my_test.js\n```\n\n# Enable/Disable real HTTP request\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\nFor disabling real http requests.\n\n```js\nnock.disableNetConnect();\n```\n\nSo, if you try to request any host not 'nocked', it will thrown an `NetConnectNotAllowedError`.\n\n```js\nnock.disableNetConnect();\nvar req = http.get('http://google.com/');\nreq.on('error', function(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: Not allow net connect for \"google.com:80\"\n```\n\nFor enabling real HTTP requests (the default behaviour).\n\n```js\nnock.enableNetConnect();\n```\n\nYou could allow real HTTP request for certain host names by providing a string or a regular expression for the hostname:\n\n```js\n// using a string\nnock.enableNetConnect('amazon.com');\n\n// or a RegExp\nnock.enableNetConnect(/(amazon|github).com/);\n\nhttp.get('http://www.amazon.com/');\nhttp.get('http://github.com/'); // only for second example\n\n// This request will be done!\nhttp.get('http://google.com/');\n// this will throw NetConnectNotAllowedError with message:\n// Nock: Not allow net connect for \"google.com:80\"\n```\n\nA common use case when testing local endpoints would be to disable all but local host, then adding in additional nocks for external requests:\n\n```js\nnock.disableNetConnect();\nnock.enableNetConnect('127.0.0.1'); //Allow localhost connections so we can test local routes and mock servers.\n```\nThen when 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 answers 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.\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\nvar 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.reset()` 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\nvar 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* `headers` - the headers of the reply\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 them 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 = function(body, aRecordedBody) {\n    if (typeof(body) !== 'string' || typeof(aRecordedBody) !== 'string') {\n      return body;\n    }\n\n    var recordedBodyResult = /timestamp:([0-9]+)/.exec(aRecordedBody);\n    if (!recordedBodyResult) {\n      return body;\n    }\n\n    var recordedTimestamp = recordedBodyResult[1];\n    return body.replace(/(timestamp):([0-9]+)/g, function(match, key, value) {\n      return key + ':' + recordedTimestamp;\n    });\n  };\n});\n```\n\nAlternatively, if you need to pre-process the captured nock definitions before using them (e.g. to add scope filtering) then you can use `nock.loadDefs(path)` and `nock.define(nockDefs)`. Shown here is scope filtering for Dropbox node module 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).\nvar nockDefs = nock.loadDefs(pathToJson);\nnockDefs.forEach(function(def) {\n  //  Do something with the definition object e.g. scope filtering.\n  def.options = def.options || {};\n  def.options.filteringScope = function(scope) {\n    return /^https:\\/\\/api[0-9]*.dropbox.com/.test(scope);\n  };\n}\n\n//  Load the nocks from pre-processed definitions.\nvar nocks = nock.define(nockDefs);\n```\n\n## `enable_reqheaders_recording` option\n\nRecording request headers by default is deemed more trouble than its worth as some of them depend on the timestamp or other values that may change after the tests have been recorder 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\nvar appendLogToFile = function(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 it's 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()\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```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\nvar interceptor = nock('http://example.org')\n  .get('somePath');\nnock.removeInterceptor(interceptor);\n```\n\n# Events\n\nA scope emits the following events:\n\n* `emit('request', function(req, interceptor))`;\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', function(req) {\n\n});\n```\n\n# Nock Back\n\nfixture recording support and playback\n\n## Setup\n\n**You must specify a fixture directory before using, for example:\n\nIn your test helper\n\n```javascript\nvar 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\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```javascript\nvar nockBack = require('nock').back;\nvar request = require('request');\nnockBack.setMode('record');\n\nnockBack.fixtures = __dirname + '/nockFixtures'; //this only needs to be set once in your test helper\n\nvar before = function(scope) {\n  scope.filteringRequestBody = function(body, aRecordedBody) {\n    if (typeof(body) !== 'string' || typeof(aRecordedBody) !== 'string') {\n      return body;\n    }\n\n    var recordedBodyResult = /timestamp:([0-9]+)/.exec(aRecordedBody);\n    if (!recordedBodyResult) {\n      return body;\n    }\n\n    var recordedTimestamp = recordedBodyResult[1];\n    return body.replace(/(timestamp):([0-9]+)/g, function(match, key, value) {\n      return key + ':' + recordedTimestamp;\n    });\n  };\n}\n\n// recording of the fixture\nnockBack('zomboFixture.json', function(nockDone) {\n  request.get('http://zombo.com', function(err, res, body) {\n    nockDone();\n\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```\nreturn nockBack('promisedFixture.json')\n  .then(({nockDone, context}) => {\n    //  do your tests returning a promise and chain it with\n    //  `.then(nockDone);`\n  });\n});\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 array scopes to save to the fixture\n- `recorder`: custom options to pass to the recorder\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 programatically, 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- lockdown: use recorded nocks, disables all http calls even when not nocked, doesn't record\n\n# Debugging\nNock uses debug, so just run with environmental variable DEBUG set to nock.*\n\n```js\n$ DEBUG=nock.* node my_test.js\n```\n\n# PROTIP\n\nIf you don't want to match the request body you can use this trick (by @theycallmeswift):\n\n```js\nvar scope = nock('http://api.myservice.com')\n  .filteringRequestBody(function(body) {\n    return '*';\n  })\n  .post('/some_uri', '*')\n  .reply(200, 'OK');\n```\n\n# Contributing\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## Commit Message conventions\n\n`nock` releases are automated using [semantic-release](https://github.com/semantic-release/semantic-release).\nTo automatically calculate the correct version number as well as changelogs,\nthree commit message conventions need to be followed\n\n- Commit bug fixes with `fix: ...` or `fix(scope): ...` prefix in commit subject\n- Commit new features with `feat: ...` or `feat(scope): ...` prefix in commit subject\n- Commit breaking changes by adding `BREAKING CHANGE: ` in the commit body\n  (not the subject line)\n\nOther helpful conventions are\n\n- Commit test files with `test: ...` or `test(scope): ...` prefix\n- Commit changes to `package.json`, `.gitignore` and other meta files with\n  `chore(filename-without-ext): ...`\n- Commit changes to README files or comments with `docs: ...`\n- Code style changes with `style: standard`\n\nThe commit message(s) of a pull request can be fixed using the `squash & merge` button.\n\n## Generate README TOC\n\nMake sure to update the README's table of contents whenever you update the README using the following npm script.\n\n```\n$ npm run toc\n```\n\n## Running tests\n\n```\n$ npm test\n```\n\n### Airplane mode\n\nSome of the tests depend on online connectivity. To skip them, set the `AIRPLANE` environment variable to some value.\n\n```\n$ export AIRPLANE=true\n$ npm test\n```\n\n# License\n\n[MIT](LICENSE)\n\nCopyright (c) 2011-2017 [Pedro Teixeira](http://about.me/pedroteixeira) and other [contributors](https://github.com/node-nock/nock/graphs/contributors).\n","maintainers":[{"name":"aleung","email":"leoliang@gmail.com"}],"time":{"modified":"2022-04-04T12:38:10.938Z","created":"2017-12-21T17:46:29.615Z","9.1.5":"2017-12-21T17:46:29.615Z","9.1.51":"2018-02-06T10:25:30.990Z"},"homepage":"https://github.com/aleung/nock#readme","repository":{"type":"git","url":"git+https://github.com/aleung/nock.git"},"contributors":[{"name":"Bin Chang","url":"https://github.com/BinChang"},{"name":"Roman Hotsiy","url":"https://github.com/RomanGotsiy"},{"name":"Jeffrey Jagoda","url":"https://github.com/jagoda"},{"name":"Hidenari Nozaki","url":"https://github.com/ghiden"},{"name":"Ken Sheedlo","url":"https://github.com/ksheedlo"},{"name":"Douglas Eggleton","url":"https://github.com/douglaseggleton"},{"name":"José F. Romaniello","url":"https://github.com/jfromaniello"},{"name":"Benjamin Urban","url":"https://github.com/benurb"},{"name":"Justin","url":"https://github.com/justincy"},{"name":"Brett Porter"},{"name":"Matt Olson"},{"name":"Rémy HUBSCHER"},{"name":"Roly Fentanes"},{"name":"Alexander Simmerl"},{"name":"Pedro Teixeira"},{"name":"Nuno Job"},{"name":"Ian Young"},{"name":"nilsbunger"},{"name":"bacchusrx","email":"bacchusrx@eightstar.ca"},{"name":"Fabiano França"},{"name":"Sascha Drews"},{"name":"Mike Swift"},{"name":"James Herdman"},{"name":"David Björklund"},{"name":"Andrew Kramolisch"},{"name":"Balazs Nagy"},{"name":"Brian J Brennan"},{"name":"Attila Incze"},{"name":"Mac Angell"},{"name":"Tom Hosford"},{"name":"Aurélien Thieriot"},{"name":"Alex Zylman"},{"name":"Celestino Gomes","email":"contact@tinogomes.com"},{"name":"David Rousselie"},{"name":"spenceralger"},{"name":"Ivan Erceg","email":"ivan@softwaremarbles.com","url":"https://github.com/ierceg"},{"name":"Keith Laban","email":"kelaban17@gmail.com","url":"https://github.com/kelaban"},{"name":"Rui Marinho","email":"ruipmarinho@gmail.com","url":"https://github.com/ruimarinho"},{"name":"David Pate","email":"davidtpate@gmail.com","url":"https://github.com/DavidTPate"},{"name":"Matt Oakes","url":"https://github.com/matto1990"},{"name":"Ian Walker-Sperber","url":"https://github.com/ianwsperber"}],"author":{"name":"Pedro Teixeira","email":"pedro.teixeira@gmail.com"},"bugs":{"url":"http://github.com/aleung/nock/issues"},"license":"MIT","readmeFilename":"README.md"}