-
Notifications
You must be signed in to change notification settings - Fork 0
/
package.json
252 lines (252 loc) · 46.8 KB
/
package.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
{
"_args": [
[
{
"raw": "nock@https://registry.npmjs.org/nock/-/nock-8.2.2.tgz",
"scope": null,
"escapedName": "nock",
"name": "nock",
"rawSpec": "https://registry.npmjs.org/nock/-/nock-8.2.2.tgz",
"spec": "https://registry.npmjs.org/nock/-/nock-8.2.2.tgz",
"type": "remote"
},
"/Users/jennyphan/AngularToolingSamples/Angular4/aboutMe-app/functions/node_modules/firebase-admin"
]
],
"_from": "nock@https://registry.npmjs.org/nock/-/nock-8.2.2.tgz",
"_id": "nock@8.2.2",
"_inCache": true,
"_location": "/firebase-admin/nock",
"_phantomChildren": {},
"_requested": {
"raw": "nock@https://registry.npmjs.org/nock/-/nock-8.2.2.tgz",
"scope": null,
"escapedName": "nock",
"name": "nock",
"rawSpec": "https://registry.npmjs.org/nock/-/nock-8.2.2.tgz",
"spec": "https://registry.npmjs.org/nock/-/nock-8.2.2.tgz",
"type": "remote"
},
"_requiredBy": [],
"_resolved": "https://registry.npmjs.org/nock/-/nock-8.2.2.tgz",
"_shasum": "fe9d1b9d30e899e886bd79c420b06de7e90c478f",
"_shrinkwrap": null,
"_spec": "nock@https://registry.npmjs.org/nock/-/nock-8.2.2.tgz",
"_where": "/Users/jennyphan/AngularToolingSamples/Angular4/aboutMe-app/functions/node_modules/firebase-admin",
"author": {
"name": "Pedro Teixeira",
"email": "pedro.teixeira@gmail.com"
},
"bugs": {
"url": "http://github.com/node-nock/nock/issues"
},
"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"
}
],
"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.9.0",
"mkdirp": "^0.5.0",
"propagate": "0.4.0",
"qs": "^6.0.2"
},
"description": "HTTP Server mocking for Node.js",
"devDependencies": {
"async": "^2.1.1",
"aws-sdk": "^2.0.15",
"browserify": "^13.0.0",
"changelog": "^1.0.7",
"coveralls": "^2.11.2",
"hyperquest": "^1.3.0",
"isomorphic-fetch": "^2.2.0",
"istanbul": "^0.4.2",
"jshint": "^2.5.6",
"markdown-toc": "^0.13.0",
"needle": "^1.0.0",
"node-static": "^0.7.7",
"nyc": "^8.3.0",
"pre-commit": "1.1.2",
"request": "2.71.0",
"request-promise": "^2.0.1",
"restify": "^4.0.4",
"restler": "3.4.0",
"rimraf": "^2.3.2",
"superagent": "^1.4.0",
"tap": "^5.7.0",
"zombie": "^4.2.1"
},
"engines": [
"node >= 0.10.0"
],
"homepage": "https://github.com/node-nock/nock#readme",
"license": "MIT",
"main": "./index",
"name": "nock",
"optionalDependencies": {},
"pre-commit": [
"jshint",
"coverage"
],
"readme": "# Nock\n\n[![Build Status](https://travis-ci.org/node-nock/nock.svg?branch=master)](https://travis-ci.org/node-nock/nock)\n[![Coverage Status](https://coveralls.io/repos/github/node-nock/nock/badge.svg?branch=master)](https://coveralls.io/github/node-nock/nock?branch=master)\n[![Known Vulnerabilities](https://snyk.io/test/npm/nock/badge.svg)](https://snyk.io/test/npm/nock)\n[![Chat](https://img.shields.io/badge/help-gitter-eb9348.svg?style=flat)](https://gitter.im/node-nock/nock)\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- [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- [Logging](#logging)\n- [Restoring](#restoring)\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- [How does it work?](#how-does-it-work)\n- [Debugging](#debugging)\n- [PROTIP](#protip)\n- [Generate Changelog](#generate-changelog)\n- [License](#license)\n\n<!-- tocstop -->\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 | 8.x |\n| 5 | up to 8.x |\n| 6 | 8.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 an 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.\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');\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\nscope('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) 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 and port through) of a nock through a function. This filtering functions is defined at the moment of defining the nock's scope through its optional `options` parameters:\n\nThis can be useful, for instance, if you have a node module that randomly changes subdomains to which it sends requests (e.g. Dropbox node module is like that)\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\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# 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**: restore does not clear the interceptor list. Use [nock.cleanAll()](#cleanall) if you expect the interceptor list to be empty.\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\nAs default, if you do not mock a host, a real HTTP request will do, but sometimes you should not permit real HTTP request, 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, specially 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\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!\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 call back function will be 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(aRecodedBody);\n if (!recodedBodyResult) {\n return body;\n }\n\n var recordedTimestamp = recodedBodyResult[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\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# 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# 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\n# Generate Changelog\n\n```\n$ npm run changelog\n```\n\n# License\n\n(The MIT License)\n\nCopyright (c) 2011-2015 Pedro Teixeira. http://about.me/pedroteixeira\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/node-nock/nock.git"
},
"scripts": {
"changelog": "changelog nock all -m > CHANGELOG.md",
"coverage": "nyc --reporter=lcov tap --harmony ./tests/test_*.js",
"coveralls": "cat ./coverage/lcov.info | coveralls",
"jshint": "jshint lib/*.js",
"test": "tap --harmony ./tests/test_*.js"
},
"tags": [
"Mock",
"HTTP",
"testing",
"isolation"
],
"version": "8.2.2"
}