UNPKG

51.1 kBMarkdownView Raw
1# Nock
2
3[![npm](https://img.shields.io/npm/v/nock.svg)][npmjs]
4[![Build Status](https://travis-ci.org/nock/nock.svg)][build]
5![Coverage Status](http://img.shields.io/badge/coverage-100%25-brightgreen.svg)
6[![Greenkeeper](https://badges.greenkeeper.io/nock/nock.svg)](https://greenkeeper.io/)
7[![Backers on Open Collective](https://opencollective.com/nock/backers/badge.svg)](#backers)
8[![Sponsors on Open Collective](https://opencollective.com/nock/sponsors/badge.svg)](#sponsors)
9
10[npmjs]: https://www.npmjs.com/package/nock
11[build]: https://travis-ci.org/nock/nock
12
13HTTP server mocking and expectations library for Node.js
14
15Nock can be used to test modules that perform HTTP requests in isolation.
16
17For 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.
18
19**Table of Contents**
20
21<!-- toc -->
22
23- [How does it work?](#how-does-it-work)
24- [Install](#install)
25 - [Node version support](#node-version-support)
26- [Usage](#usage)
27 - [READ THIS! - About interceptors](#read-this---about-interceptors)
28 - [Specifying hostname](#specifying-hostname)
29 - [Specifying path](#specifying-path)
30 - [Specifying request body](#specifying-request-body)
31 - [Specifying request query string](#specifying-request-query-string)
32 - [Specifying replies](#specifying-replies)
33 - [Access original request and headers](#access-original-request-and-headers)
34 - [Replying with errors](#replying-with-errors)
35 - [Specifying headers](#specifying-headers)
36 - [Header field names are case-insensitive](#header-field-names-are-case-insensitive)
37 - [Specifying Request Headers](#specifying-request-headers)
38 - [Specifying Reply Headers](#specifying-reply-headers)
39 - [Default Reply Headers](#default-reply-headers)
40 - [Including Content-Length Header Automatically](#including-content-length-header-automatically)
41 - [Including Date Header Automatically](#including-date-header-automatically)
42 - [HTTP Verbs](#http-verbs)
43 - [Support for HTTP and HTTPS](#support-for-http-and-https)
44 - [Non-standard ports](#non-standard-ports)
45 - [Repeat response n times](#repeat-response-n-times)
46 - [Delay the response body](#delay-the-response-body)
47 - [Delay the response](#delay-the-response)
48 - [Delay the connection](#delay-the-connection)
49 - [Socket timeout](#socket-timeout)
50 - [Chaining](#chaining)
51 - [Scope filtering](#scope-filtering)
52 - [Conditional scope filtering](#conditional-scope-filtering)
53 - [Path filtering](#path-filtering)
54 - [Request Body filtering](#request-body-filtering)
55 - [Request Headers Matching](#request-headers-matching)
56 - [Optional Requests](#optional-requests)
57 - [Allow **unmocked** requests on a mocked hostname](#allow-unmocked-requests-on-a-mocked-hostname)
58- [Expectations](#expectations)
59 - [.isDone()](#isdone)
60 - [.cleanAll()](#cleanall)
61 - [.abortPendingRequests()](#abortpendingrequests)
62 - [.persist()](#persist)
63 - [.pendingMocks()](#pendingmocks)
64 - [.activeMocks()](#activemocks)
65 - [.isActive()](#isactive)
66- [Logging](#logging)
67- [Restoring](#restoring)
68- [Activating](#activating)
69- [Turning Nock Off (experimental!)](#turning-nock-off-experimental)
70- [Enable/Disable real HTTP requests](#enabledisable-real-http-requests)
71 - [Disabling requests](#disabling-requests)
72 - [Enabling requests](#enabling-requests)
73 - [Resetting NetConnect](#resetting-netconnect)
74- [Recording](#recording)
75 - [`dont_print` option](#dont_print-option)
76 - [`output_objects` option](#output_objects-option)
77 - [`enable_reqheaders_recording` option](#enable_reqheaders_recording-option)
78 - [`logging` option](#logging-option)
79 - [`use_separator` option](#use_separator-option)
80 - [.removeInterceptor()](#removeinterceptor)
81- [Events](#events)
82 - [Global no match event](#global-no-match-event)
83- [Nock Back](#nock-back)
84 - [Setup](#setup)
85 - [Options](#options)
86 - [Usage](#usage-1)
87 - [Options](#options-1)
88 - [Example](#example)
89 - [Modes](#modes)
90- [Common issues](#common-issues)
91 - [Axios](#axios)
92- [Debugging](#debugging)
93- [Contributing](#contributing)
94- [Contributors](#contributors)
95- [Sponsors](#sponsors)
96- [License](#license)
97
98<!-- tocstop -->
99
100## How does it work?
101
102Nock works by overriding Node's `http.request` function. Also, it overrides `http.ClientRequest` too to cover for modules that use it directly.
103
104## Install
105
106```sh
107$ npm install --save-dev nock
108```
109
110### Node version support
111
112The latest version of nock supports all currently maintained Node versions, see [Node Release Schedule](https://github.com/nodejs/Release#release-schedule)
113
114Here is a list of past nock versions with respective node version support
115
116| node | nock |
117| ---- | --------- |
118| 0.10 | up to 8.x |
119| 0.11 | up to 8.x |
120| 0.12 | up to 8.x |
121| 4 | up to 9.x |
122| 5 | up to 8.x |
123| 7 | up to 9.x |
124| 9 | up to 9.x |
125
126## Usage
127
128On your test, you can setup your mocking object like this:
129
130```js
131const nock = require('nock')
132
133const scope = nock('https://api.github.com')
134 .get('/repos/atom/atom/license')
135 .reply(200, {
136 license: {
137 key: 'mit',
138 name: 'MIT License',
139 spdx_id: 'MIT',
140 url: 'https://api.github.com/licenses/mit',
141 node_id: 'MDc6TGljZW5zZTEz',
142 },
143 })
144```
145
146This setup says that we will intercept every HTTP call to `https://api.github.com`.
147
148It will intercept an HTTPS GET request to `/repos/atom/atom/license`, reply with
149a status 200, and the body will contain a (partial) response in JSON.
150
151### READ THIS! - About interceptors
152
153When you setup an interceptor for a URL and that interceptor is used, it is removed from the interceptor list.
154This means that you can intercept 2 or more calls to the same URL and return different things on each of them.
155It 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.
156If you don’t want interceptors to be removed as they are used, you can use the [.persist()](#persist) method.
157
158### Specifying hostname
159
160The request hostname can be a string or a RegExp.
161
162```js
163const scope = nock('http://www.example.com')
164 .get('/resource')
165 .reply(200, 'domain matched')
166```
167
168```js
169const scope = nock(/example\.com/)
170 .get('/resource')
171 .reply(200, 'domain regex matched')
172```
173
174> Note: You can choose to include or not the protocol in the hostname matching.
175
176### Specifying path
177
178The request path can be a string, a RegExp or a filter function and you can use any [HTTP verb](#http-verbs).
179
180Using a string:
181
182```js
183const scope = nock('http://www.example.com')
184 .get('/resource')
185 .reply(200, 'path matched')
186```
187
188Using a regular expression:
189
190```js
191const scope = nock('http://www.example.com')
192 .get(/source$/)
193 .reply(200, 'path using regex matched')
194```
195
196Using a function:
197
198```js
199const scope = nock('http://www.example.com')
200 .get(uri => uri.includes('cats'))
201 .reply(200, 'path using function matched')
202```
203
204### Specifying request body
205
206You can specify the request body to be matched as the second argument to the `get`, `post`, `put` or `delete` specifications. There are five types of second argument allowed:
207
208**String**: nock will exact match the stringified request body with the provided string
209
210```js
211nock('http://www.example.com')
212 .post('/login', 'username=pgte&password=123456')
213 .reply(200, { id: '123ABC' })
214```
215
216**Buffer**: nock will exact match the stringified request body with the provided buffer
217
218```js
219nock('http://www.example.com')
220 .post('/login', Buffer.from([0xff, 0x11]))
221 .reply(200, { id: '123ABC' })
222```
223
224**RegExp**: nock will test the stringified request body against the provided RegExp
225
226```js
227nock('http://www.example.com')
228 .post('/login', /username=\w+/gi)
229 .reply(200, { id: '123ABC' })
230```
231
232**JSON object**: nock will exact match the request body with the provided object. In order to increase flexibility, nock also supports RegExp as an attribute value for the keys:
233
234```js
235nock('http://www.example.com')
236 .post('/login', { username: 'pgte', password: /.+/i })
237 .reply(200, { id: '123ABC' })
238```
239
240**Function**: nock will evaluate the function providing the request body object as first argument. Return true if it should be considered a match:
241
242```js
243nock('http://www.example.com')
244 .post('/login', body => body.username && body.password)
245 .reply(200, { id: '123ABC' })
246```
247
248In case you need to perform a partial matching on a complex, nested request body you should have a look at libraries like [lodash.matches](https://lodash.com/docs/#matches). Indeed, partial matching can be achieved as:
249
250```js
251nock('http://www.example.com')
252 .post('/user', _.matches({ address: { country: 'US' } }))
253 .reply(200, { id: '123ABC' })
254```
255
256### Specifying request query string
257
258Nock understands query strings. Search parameters can be included as part of the path:
259
260```js
261nock('http://example.com')
262 .get('/users?foo=bar')
263 .reply(200)
264```
265
266Instead of placing the entire URL, you can specify the query part as an object:
267
268```js
269nock('http://example.com')
270 .get('/users')
271 .query({ name: 'pedro', surname: 'teixeira' })
272 .reply(200, { results: [{ id: 'pgte' }] })
273```
274
275Nock supports array-style/object-style query parameters. The encoding format matches with request module.
276
277```js
278nock('http://example.com')
279 .get('/users')
280 .query({
281 names: ['alice', 'bob'],
282 tags: {
283 alice: ['admin', 'tester'],
284 bob: ['tester'],
285 },
286 })
287 .reply(200, { results: [{ id: 'pgte' }] })
288```
289
290A `URLSearchParams` instance can be provided.
291
292```js
293const params = new URLSearchParams({ foo: 'bar' })
294
295nock('http://example.com')
296 .get('/')
297 .query(params)
298 .reply(200)
299```
300
301Nock supports passing a function to query. The function determines if the actual query matches or not.
302
303```js
304nock('http://example.com')
305 .get('/users')
306 .query(actualQueryObject => {
307 // do some compare with the actual Query Object
308 // return true for matched
309 // return false for not matched
310 return true
311 })
312 .reply(200, { results: [{ id: 'pgte' }] })
313```
314
315To mock the entire url regardless of the passed query string:
316
317```js
318nock('http://example.com')
319 .get('/users')
320 .query(true)
321 .reply(200, { results: [{ id: 'pgte' }] })
322```
323
324A query string that is already [URL encoded](https://en.wikipedia.org/wiki/Percent-encoding) can be
325matched by passing the `encodedQueryParams` flag in the options when creating the Scope.
326
327```js
328nock('http://example.com', { encodedQueryParams: true })
329 .get('/users')
330 .query('foo%5Bbar%5D%3Dhello%20world%21')
331 .reply(200, { results: [{ id: 'pgte' }] })
332```
333
334### Specifying replies
335
336You can specify the return status code for a path on the first argument of reply like this:
337
338```js
339const scope = nock('http://myapp.iriscouch.com')
340 .get('/users/1')
341 .reply(404)
342```
343
344You can also specify the reply body as a string:
345
346```js
347const scope = nock('http://www.google.com')
348 .get('/')
349 .reply(200, 'Hello from Google!')
350```
351
352or as a JSON-encoded object:
353
354```js
355const scope = nock('http://myapp.iriscouch.com')
356 .get('/')
357 .reply(200, {
358 username: 'pgte',
359 email: 'pedro.teixeira@gmail.com',
360 _id: '4324243fsd',
361 })
362```
363
364or even as a file:
365
366```js
367const scope = nock('http://myapp.iriscouch.com')
368 .get('/')
369 .replyWithFile(200, __dirname + '/replies/user.json', {
370 'Content-Type': 'application/json',
371 })
372```
373
374Instead of an object or a buffer you can also pass in a callback to be evaluated for the value of the response body:
375
376```js
377const scope = nock('http://www.google.com')
378 .post('/echo')
379 .reply(201, (uri, requestBody) => requestBody)
380```
381
382In Nock 11.x it was possible to invoke `.reply()` with a status code and a
383function that returns an array containing a status code and body. (The status
384code from the array would take precedence over the one passed directly to
385reply.) This is no longer allowed. In 12.x, either call `.reply()` with a
386status code and a function that returns the body, or call it with a single
387argument: a function that returns an array containing both the status code and
388body.
389
390An asynchronous function that gets an error-first callback as its last argument also works:
391
392```js
393const scope = nock('http://www.google.com')
394 .post('/echo')
395 .reply(201, (uri, requestBody, cb) => {
396 fs.readFile('cat-poems.txt', cb) // Error-first callback
397 })
398```
399
400In Nock 11 and later, if an error is passed to the callback, Nock will rethrow it as a programmer error.
401In Nock 10 and earlier, the error was sent in the response body, with a 500 HTTP response status code.
402
403You can also return the status code and body using just one function:
404
405```js
406const scope = nock('http://www.google.com')
407 .post('/echo')
408 .reply((uri, requestBody) => {
409 return [
410 201,
411 'THIS IS THE REPLY BODY',
412 { header: 'value' }, // optional headers
413 ]
414 })
415```
416
417or, use an error-first callback that also gets the status code:
418
419```js
420const scope = nock('http://www.google.com')
421 .post('/echo')
422 .reply((uri, requestBody, cb) => {
423 setTimeout(() => cb(null, [201, 'THIS IS THE REPLY BODY']), 1000)
424 })
425```
426
427A Stream works too:
428
429```js
430const scope = nock('http://www.google.com')
431 .get('/cat-poems')
432 .reply(200, (uri, requestBody) => {
433 return fs.createReadStream('cat-poems.txt')
434 })
435```
436
437#### Access original request and headers
438
439If you're using the reply callback style, you can access the original client request using `this.req` like this:
440
441```js
442const scope = nock('http://www.google.com')
443 .get('/cat-poems')
444 .reply(function(uri, requestBody) {
445 console.log('path:', this.req.path)
446 console.log('headers:', this.req.headers)
447 // ...
448 })
449```
450
451> Note: Remember to use normal `function` in that case, as arrow functions are using enclosing scope for `this` binding.
452
453#### Replying with errors
454
455You can reply with an error like this:
456
457```js
458nock('http://www.google.com')
459 .get('/cat-poems')
460 .replyWithError('something awful happened')
461```
462
463JSON error responses are allowed too:
464
465```js
466nock('http://www.google.com')
467 .get('/cat-poems')
468 .replyWithError({
469 message: 'something awful happened',
470 code: 'AWFUL_ERROR',
471 })
472```
473
474> Note: This will emit an `error` event on the `request` object, not the reply.
475
476### Specifying headers
477
478#### Header field names are case-insensitive
479
480Per [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.
481
482#### Specifying Request Headers
483
484You can specify the request headers like this:
485
486```js
487const scope = nock('http://www.example.com', {
488 reqheaders: {
489 authorization: 'Basic Auth',
490 },
491})
492 .get('/')
493 .reply(200)
494```
495
496Or you can use a regular expression or function to check the header values. The
497function will be passed the header value.
498
499```js
500const scope = nock('http://www.example.com', {
501 reqheaders: {
502 'X-My-Headers': headerValue => headerValue.includes('cats'),
503 'X-My-Awesome-Header': /Awesome/i,
504 },
505})
506 .get('/')
507 .reply(200)
508```
509
510If `reqheaders` is not specified or if `host` is not part of it, Nock will automatically add `host` value to request header.
511
512If no request headers are specified for mocking then Nock will automatically skip matching of request headers. Since the `host` header is a special case which may get automatically inserted by Nock, its matching is skipped unless it was _also_ specified in the request being mocked.
513
514You can also have Nock fail the request if certain headers are present:
515
516```js
517const scope = nock('http://www.example.com', {
518 badheaders: ['cookie', 'x-forwarded-for'],
519})
520 .get('/')
521 .reply(200)
522```
523
524When invoked with this option, Nock will not match the request if any of the `badheaders` are present.
525
526Basic authentication can be specified as follows:
527
528```js
529const scope = nock('http://www.example.com')
530 .get('/')
531 .basicAuth({ user: 'john', pass: 'doe' })
532 .reply(200)
533```
534
535#### Specifying Reply Headers
536
537You can specify the reply headers like this:
538
539```js
540const scope = nock('https://api.github.com')
541 .get('/repos/atom/atom/license')
542 .reply(200, { license: 'MIT' }, { 'X-RateLimit-Remaining': 4999 })
543```
544
545Or you can use a function to generate the headers values. The function will be
546passed the request, response, and response body (if available). The body will
547be either a buffer, a stream, or undefined.
548
549```js
550const scope = nock('http://www.headdy.com')
551 .get('/')
552 .reply(200, 'Hello World!', {
553 'Content-Length': (req, res, body) => body.length,
554 ETag: () => `${Date.now()}`,
555 })
556```
557
558#### Default Reply Headers
559
560You can also specify default reply headers for all responses like this:
561
562```js
563const scope = nock('http://www.headdy.com')
564 .defaultReplyHeaders({
565 'X-Powered-By': 'Rails',
566 'Content-Type': 'application/json',
567 })
568 .get('/')
569 .reply(200, 'The default headers should come too')
570```
571
572Or you can use a function to generate the default headers values:
573
574```js
575const scope = nock('http://www.headdy.com')
576 .defaultReplyHeaders({
577 'Content-Length': (req, res, body) => body.length,
578 })
579 .get('/')
580 .reply(200, 'The default headers should come too')
581```
582
583#### Including Content-Length Header Automatically
584
585When using `scope.reply()` to set a response body manually, you can have the
586`Content-Length` header calculated automatically.
587
588```js
589const scope = nock('http://www.headdy.com')
590 .replyContentLength()
591 .get('/')
592 .reply(200, { hello: 'world' })
593```
594
595**NOTE:** this does not work with streams or other advanced means of specifying
596the reply body.
597
598#### Including Date Header Automatically
599
600You can automatically append a `Date` header to your mock reply:
601
602```js
603const scope = nock('http://www.headdy.com')
604 .replyDate()
605 .get('/')
606 .reply(200, { hello: 'world' })
607```
608
609Or provide your own `Date` object:
610
611```js
612const scope = nock('http://www.headdy.com')
613 .replyDate(new Date(2015, 0, 1))
614 .get('/')
615 .reply(200, { hello: 'world' })
616```
617
618### HTTP Verbs
619
620Nock supports any HTTP verb, and it has convenience methods for the GET, POST, PUT, HEAD, DELETE, PATCH, OPTIONS and MERGE HTTP verbs.
621
622You can intercept any HTTP verb using `.intercept(path, verb [, requestBody [, options]])`:
623
624```js
625const scope = nock('http://my.domain.com')
626 .intercept('/path', 'PATCH')
627 .reply(304)
628```
629
630### Support for HTTP and HTTPS
631
632By default nock assumes HTTP. If you need to use HTTPS you can specify the `https://` prefix like this:
633
634```js
635const scope = nock('https://secure.my.server.com')
636// ...
637```
638
639### Non-standard ports
640
641You are able to specify a non-standard port like this:
642
643```js
644const scope = nock('http://my.server.com:8081')
645 ...
646```
647
648### Repeat response n times
649
650You are able to specify the number of times to repeat the same response.
651
652```js
653nock('http://zombo.com')
654 .get('/')
655 .times(4)
656 .reply(200, 'Ok')
657
658http.get('http://zombo.com/') // respond body "Ok"
659http.get('http://zombo.com/') // respond body "Ok"
660http.get('http://zombo.com/') // respond body "Ok"
661http.get('http://zombo.com/') // respond body "Ok"
662http.get('http://zombo.com/') // respond with zombo.com result
663```
664
665Sugar syntax
666
667```js
668nock('http://zombo.com')
669 .get('/')
670 .once()
671 .reply(200, 'Ok')
672nock('http://zombo.com')
673 .get('/')
674 .twice()
675 .reply(200, 'Ok')
676nock('http://zombo.com')
677 .get('/')
678 .thrice()
679 .reply(200, 'Ok')
680```
681
682To repeat this response for as long as nock is active, use [.persist()](#persist).
683
684### Delay the response body
685
686You are able to specify the number of milliseconds that the response body should be delayed. Response header will be replied immediately.
687`delayBody(1000)` is equivalent to `delay({body: 1000})`.
688
689```js
690nock('http://my.server.com')
691 .get('/')
692 .delayBody(2000) // 2 seconds
693 .reply(200, '<html></html>')
694```
695
696NOTE: 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 its `'end'` event until after the delay.
697
698### Delay the response
699
700You are able to specify the number of milliseconds that your reply should be delayed.
701
702```js
703nock('http://my.server.com')
704 .get('/')
705 .delay(2000) // 2 seconds delay will be applied to the response header.
706 .reply(200, '<html></html>')
707```
708
709`delay()` could also be used as
710
711```
712delay({
713 head: headDelayInMs,
714 body: bodyDelayInMs
715})
716```
717
718for example
719
720```js
721nock('http://my.server.com')
722 .get('/')
723 .delay({
724 head: 2000, // header will be delayed for 2 seconds, i.e. the whole response will be delayed for 2 seconds.
725 body: 3000, // body will be delayed for another 3 seconds after header is sent out.
726 })
727 .reply(200, '<html></html>')
728```
729
730### Delay the connection
731
732`delayConnection(1000)` is equivalent to `delay({ head: 1000 })`.
733
734### Socket timeout
735
736You are able to specify the number of milliseconds that your connection should be idle, to simulate a socket timeout.
737
738```js
739nock('http://my.server.com')
740 .get('/')
741 .socketDelay(2000) // 2 seconds
742 .reply(200, '<html></html>')
743```
744
745To test a request like the following:
746
747```js
748req = http.request('http://my.server.com', res => {
749 ...
750})
751req.setTimeout(1000, () => { req.abort() })
752req.end()
753```
754
755NOTE: the timeout will be fired immediately, and will not leave the simulated connection idle for the specified period of time.
756
757### Chaining
758
759You can chain behaviour like this:
760
761```js
762const scope = nock('http://myapp.iriscouch.com')
763 .get('/users/1')
764 .reply(404)
765 .post('/users', {
766 username: 'pgte',
767 email: 'pedro.teixeira@gmail.com',
768 })
769 .reply(201, {
770 ok: true,
771 id: '123ABC',
772 rev: '946B7D1C',
773 })
774 .get('/users/123ABC')
775 .reply(200, {
776 _id: '123ABC',
777 _rev: '946B7D1C',
778 username: 'pgte',
779 email: 'pedro.teixeira@gmail.com',
780 })
781```
782
783### Scope filtering
784
785You 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.
786
787This 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.
788
789```js
790const scope = nock('https://api.dropbox.com', {
791 filteringScope: scope => /^https:\/\/api[0-9]*.dropbox.com/.test(scope),
792})
793 .get('/1/metadata/auto/Photos?include_deleted=false&list=true')
794 .reply(200)
795```
796
797### Conditional scope filtering
798
799You can also choose to filter out a scope based on your system environment (or any external factor). The filtering function is accepted at the `conditionally` field of the `options` argument.
800
801This can be useful if you only want certain scopes to apply depending on how your tests are executed.
802
803```js
804const scope = nock('https://api.myservice.com', {
805 conditionally: () => true,
806})
807```
808
809### Path filtering
810
811You can also filter the URLs based on a function.
812
813This can be useful, for instance, if you have random or time-dependent data in your URL.
814
815You can use a regexp for replacement, just like String.prototype.replace:
816
817```js
818const scope = nock('http://api.myservice.com')
819 .filteringPath(/password=[^&]*/g, 'password=XXX')
820 .get('/users/1?password=XXX')
821 .reply(200, 'user')
822```
823
824Or you can use a function:
825
826```js
827const scope = nock('http://api.myservice.com')
828 .filteringPath(path => '/ABC')
829 .get('/ABC')
830 .reply(200, 'user')
831```
832
833Note that `scope.filteringPath` is not cumulative: it should only be used once per scope.
834
835### Request Body filtering
836
837You can also filter the request body based on a function.
838
839This can be useful, for instance, if you have random or time-dependent data in your request body.
840
841You can use a regexp for replacement, just like String.prototype.replace:
842
843```js
844const scope = nock('http://api.myservice.com')
845 .filteringRequestBody(/password=[^&]*/g, 'password=XXX')
846 .post('/users/1', 'data=ABC&password=XXX')
847 .reply(201, 'OK')
848```
849
850Or you can use a function to transform the body:
851
852```js
853const scope = nock('http://api.myservice.com')
854 .filteringRequestBody(body => 'ABC')
855 .post('/', 'ABC')
856 .reply(201, 'OK')
857```
858
859If you don't want to match the request body you should omit the `body` argument from the method function:
860
861```js
862const scope = nock('http://api.myservice.com')
863 .post('/some_uri') // no body argument
864 .reply(200, 'OK')
865```
866
867### Request Headers Matching
868
869If you need to match requests only if certain request headers match, you can.
870
871```js
872const scope = nock('http://api.myservice.com')
873 .matchHeader('accept', 'application/json')
874 .get('/')
875 .reply(200, {
876 data: 'hello world',
877 })
878```
879
880You can also use a regexp for the header body.
881
882```js
883const scope = nock('http://api.myservice.com')
884 .matchHeader('User-Agent', /Mozilla\/.*/)
885 .get('/')
886 .reply(200, {
887 data: 'hello world',
888 })
889```
890
891You can also use a function for the header body.
892
893```js
894const scope = nock('http://api.myservice.com')
895 .matchHeader('content-length', val => val >= 1000)
896 .get('/')
897 .reply(200, {
898 data: 'hello world',
899 })
900```
901
902### Optional Requests
903
904By 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.
905
906```js
907const example = nock('http://example.com')
908example.pendingMocks() // []
909example.get('/pathA').reply(200)
910example.pendingMocks() // ["GET http://example.com:80/path"]
911
912// ...After a request to example.com/pathA:
913example.pendingMocks() // []
914
915example
916 .get('/pathB')
917 .optionally()
918 .reply(200)
919example.pendingMocks() // []
920
921// You can also pass a boolean argument to `optionally()`. This
922// is useful if you want to conditionally make a mocked request
923// optional.
924const getMock = optional =>
925 example
926 .get('/pathC')
927 .optionally(optional)
928 .reply(200)
929
930getMock(true)
931example.pendingMocks() // []
932getMock(false)
933example.pendingMocks() // ["GET http://example.com:80/pathC"]
934```
935
936### Allow **unmocked** requests on a mocked hostname
937
938If 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:
939
940```js
941const scope = nock('http://my.existing.service.com', { allowUnmocked: true })
942 .get('/my/url')
943 .reply(200, 'OK!')
944
945// GET /my/url => goes through nock
946// GET /other/url => actually makes request to the server
947```
948
949> Note: When applying `{allowUnmocked: true}`, if the request is made to the real server, no interceptor is removed.
950
951## Expectations
952
953Every 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.
954
955Calls 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.
956
957Example:
958
959```js
960const scope = nock('http://google.com')
961 .get('/')
962 .reply(200, 'Hello from Google!')
963
964// do some stuff
965
966setTimeout(() => {
967 // Will throw an assertion error if meanwhile a "GET http://google.com" was
968 // not performed.
969 scope.done()
970}, 5000)
971```
972
973### .isDone()
974
975You can call `isDone()` on a single expectation to determine if the expectation was met:
976
977```js
978const scope = nock('http://google.com')
979 .get('/')
980 .reply(200)
981
982scope.isDone() // will return false
983```
984
985It is also available in the global scope, which will determine if all expectations have been met:
986
987```js
988nock.isDone()
989```
990
991### .cleanAll()
992
993You can cleanup all the prepared mocks (could be useful to cleanup some state after a failed test) like this:
994
995```js
996nock.cleanAll()
997```
998
999### .abortPendingRequests()
1000
1001You can abort all current pending request like this:
1002
1003```js
1004nock.abortPendingRequests()
1005```
1006
1007### .persist()
1008
1009You can make all the interceptors for a scope persist by calling `.persist()` on it:
1010
1011```js
1012const scope = nock('http://example.com')
1013 .persist()
1014 .get('/')
1015 .reply(200, 'Persisting all the way')
1016```
1017
1018Note that while a persisted scope will always intercept the requests, it is considered "done" after the first interception.
1019
1020If you want to stop persisting an individual persisted mock you can call `persist(false)`:
1021
1022```js
1023const scope = nock('http://example.com')
1024 .persist()
1025 .get('/')
1026 .reply(200, 'ok')
1027
1028// Do some tests ...
1029
1030scope.persist(false)
1031```
1032
1033You can also use `nock.cleanAll()` which removes all mocks, including persistent mocks.
1034
1035To specify an exact number of times that nock should repeat the response, use [.times()](#repeat-response-n-times).
1036
1037### .pendingMocks()
1038
1039If a scope is not done, you can inspect the scope to infer which ones are still pending using the `scope.pendingMocks()` function:
1040
1041```js
1042if (!scope.isDone()) {
1043 console.error('pending mocks: %j', scope.pendingMocks())
1044}
1045```
1046
1047It is also available in the global scope:
1048
1049```js
1050console.error('pending mocks: %j', nock.pendingMocks())
1051```
1052
1053### .activeMocks()
1054
1055You 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.
1056
1057You probably don't need to use this - it mainly exists as a mechanism to recreate the previous (now-changed) behavior of `pendingMocks()`.
1058
1059```js
1060console.error('active mocks: %j', scope.activeMocks())
1061```
1062
1063It is also available in the global scope:
1064
1065```js
1066console.error('active mocks: %j', nock.activeMocks())
1067```
1068
1069### .isActive()
1070
1071Your tests may sometimes want to deactivate the nock interceptor.
1072Once deactivated, nock needs to be re-activated to work.
1073You can check if nock interceptor is active or not by using `nock.isActive()`.
1074Sample:
1075
1076```js
1077if (!nock.isActive()) {
1078 nock.activate()
1079}
1080```
1081
1082## Logging
1083
1084Nock can log matches if you pass in a log function like this:
1085
1086```js
1087const scope = nock('http://google.com')
1088 .log(console.log)
1089 ...
1090```
1091
1092## Restoring
1093
1094You can restore the HTTP interceptor to the normal unmocked behaviour by calling:
1095
1096```js
1097nock.restore()
1098```
1099
1100**note 1**: restore does not clear the interceptor list. Use [nock.cleanAll()](#cleanall) if you expect the interceptor list to be empty.
1101
1102**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.
1103
1104## Activating
1105
1106Only for cases where nock has been deactivated using [nock.restore()](#restoring), you can reactivate the HTTP interceptor to start intercepting HTTP calls using:
1107
1108```js
1109nock.activate()
1110```
1111
1112**note**: To check if nock HTTP interceptor is active or inactive, use [nock.isActive()](#isactive).
1113
1114## Turning Nock Off (experimental!)
1115
1116You can bypass Nock completely by setting the `NOCK_OFF` environment variable to `"true"`.
1117
1118This way you can have your tests hit the real servers just by switching on this environment variable.
1119
1120```js
1121$ NOCK_OFF=true node my_test.js
1122```
1123
1124## Enable/Disable real HTTP requests
1125
1126By 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.
1127
1128### Disabling requests
1129
1130For disabling real http requests.
1131
1132```js
1133nock.disableNetConnect()
1134```
1135
1136So, if you try to request any host not 'nocked', it will throw a `NetConnectNotAllowedError`.
1137
1138```js
1139nock.disableNetConnect()
1140const req = http.get('http://google.com/')
1141req.on('error', err => {
1142 console.log(err)
1143})
1144// The returned `http.ClientRequest` will emit an error event (or throw if you're not listening for it)
1145// This code will log a NetConnectNotAllowedError with message:
1146// Nock: Disallowed net connect for "google.com:80"
1147```
1148
1149### Enabling requests
1150
1151For enabling any real HTTP requests (the default behavior):
1152
1153```js
1154nock.enableNetConnect()
1155```
1156
1157You could allow real HTTP requests for certain host names by providing a string or a regular expression for the hostname:
1158
1159```js
1160// Using a string
1161nock.enableNetConnect('amazon.com')
1162
1163// Or a RegExp
1164nock.enableNetConnect(/(amazon|github)\.com/)
1165
1166http.get('http://www.amazon.com/')
1167http.get('http://github.com/')
1168
1169http.get('http://google.com/')
1170// This will throw NetConnectNotAllowedError with message:
1171// Nock: Disallowed net connect for "google.com:80"
1172```
1173
1174A common use case when testing local endpoints would be to disable all but localhost, then add in additional nocks for external requests:
1175
1176```js
1177nock.disableNetConnect()
1178// Allow localhost connections so we can test local routes and mock servers.
1179nock.enableNetConnect('127.0.0.1')
1180```
1181
1182### Resetting NetConnect
1183
1184When you're done with the test, you probably want to set everything back to normal:
1185
1186```js
1187nock.cleanAll()
1188nock.enableNetConnect()
1189```
1190
1191## Recording
1192
1193This is a cool feature:
1194
1195Guessing what the HTTP calls are is a mess, especially if you are introducing nock on your already-coded tests.
1196
1197For these cases where you want to mock an existing live system you can record and playback the HTTP calls like this:
1198
1199```js
1200nock.recorder.rec()
1201// Some HTTP calls happen and the nock code necessary to mock
1202// those calls will be outputted to console
1203```
1204
1205Recording relies on intercepting real requests and responses and then persisting them for later use.
1206
1207In order to stop recording you should call `nock.restore()` and recording will stop.
1208
1209**ATTENTION!:** when recording is enabled, nock does no validation, nor will any mocks be enabled. Please be sure to turn off recording before attempting to use any mocks in your tests.
1210
1211### `dont_print` option
1212
1213If you just want to capture the generated code into a var as an array you can use:
1214
1215```js
1216nock.recorder.rec({
1217 dont_print: true,
1218})
1219// ... some HTTP calls
1220const nockCalls = nock.recorder.play()
1221```
1222
1223The `nockCalls` var will contain an array of strings representing the generated code you need.
1224
1225Copy and paste that code into your tests, customize at will, and you're done! You can call `nock.recorder.clear()` to remove already recorded calls from the array that `nock.recorder.play()` returns.
1226
1227(Remember that you should do this one test at a time).
1228
1229### `output_objects` option
1230
1231In 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`:
1232
1233```js
1234nock.recorder.rec({
1235 output_objects: true,
1236})
1237// ... some HTTP calls
1238const nockCallObjects = nock.recorder.play()
1239```
1240
1241The returned call objects have the following properties:
1242
1243- `scope` - the scope of the call including the protocol and non-standard ports (e.g. `'https://github.com:12345'`)
1244- `method` - the HTTP verb of the call (e.g. `'GET'`)
1245- `path` - the path of the call (e.g. `'/pgte/nock'`)
1246- `body` - the body of the call, if any
1247- `status` - the HTTP status of the reply (e.g. `200`)
1248- `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)
1249- `headers` - the headers of the reply
1250- `reqheader` - the headers of the request
1251
1252If you save this as a JSON file, you can load them directly through `nock.load(path)`. Then you can post-process them before using them in the tests. For example, to add request body filtering (shown here fixing timestamps to match the ones captured during recording):
1253
1254```js
1255nocks = nock.load(pathToJson)
1256nocks.forEach(function(nock) {
1257 nock.filteringRequestBody = (body, aRecordedBody) => {
1258 if (typeof body !== 'string' || typeof aRecordedBody !== 'string') {
1259 return body
1260 }
1261
1262 const recordedBodyResult = /timestamp:([0-9]+)/.exec(aRecordedBody)
1263 if (recordedBodyResult) {
1264 const recordedTimestamp = recordedBodyResult[1]
1265 return body.replace(/(timestamp):([0-9]+)/g, function(match, key, value) {
1266 return key + ':' + recordedTimestamp
1267 })
1268 } else {
1269 return body
1270 }
1271 }
1272})
1273```
1274
1275Alternatively, if you need to pre-process the captured nock definitions before
1276using them (e.g. to add scope filtering) then you can use `nock.loadDefs(path)`
1277and `nock.define(nockDefs)`. Shown here is scope filtering for Dropbox node
1278module which constantly changes the subdomain to which it sends the requests:
1279
1280```js
1281// Pre-process the nock definitions as scope filtering has to be defined before the nocks are defined (due to its very hacky nature).
1282const nockDefs = nock.loadDefs(pathToJson)
1283nockDefs.forEach(def => {
1284 // Do something with the definition object e.g. scope filtering.
1285 def.options = {
1286 ...def.options,
1287 filteringScope: scope => /^https:\/\/api[0-9]*.dropbox.com/.test(scope),
1288 }
1289})
1290
1291// Load the nocks from pre-processed definitions.
1292const nocks = nock.define(nockDefs)
1293```
1294
1295### `enable_reqheaders_recording` option
1296
1297Recording request headers by default is deemed more trouble than it's worth as some of them depend on the timestamp or other values that may change after the tests have been recorded thus leading to complex postprocessing of recorded tests. Thus by default the request headers are not recorded.
1298
1299The 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.
1300
1301```js
1302nock.recorder.rec({
1303 dont_print: true,
1304 output_objects: true,
1305 enable_reqheaders_recording: true,
1306})
1307```
1308
1309Note 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.
1310
1311### `logging` option
1312
1313Nock 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.
1314
1315```js
1316const appendLogToFile = content => {
1317 fs.appendFile('record.txt', content)
1318}
1319nock.recorder.rec({
1320 logging: appendLogToFile,
1321})
1322```
1323
1324### `use_separator` option
1325
1326By default, nock will wrap its output with the separator string `<<<<<<-- cut here -->>>>>>` before and after anything it prints, whether to the console or a custom log function given with the `logging` option.
1327
1328To disable this, set `use_separator` to false.
1329
1330```js
1331nock.recorder.rec({
1332 use_separator: false,
1333})
1334```
1335
1336### .removeInterceptor()
1337
1338This 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.
1339
1340Examples:
1341
1342```js
1343nock.removeInterceptor({
1344 hostname: 'localhost',
1345 path: '/mockedResource',
1346})
1347```
1348
1349```js
1350nock.removeInterceptor({
1351 hostname : 'localhost',
1352 path : '/login'
1353 method: 'POST'
1354 proto : 'https'
1355})
1356```
1357
1358```js
1359const interceptor = nock('http://example.org').get('somePath')
1360nock.removeInterceptor(interceptor)
1361```
1362
1363## Events
1364
1365A scope emits the following events:
1366
1367- `emit('request', function(req, interceptor, body))`
1368- `emit('replied', function(req, interceptor))`
1369
1370### Global no match event
1371
1372You can also listen for no match events like this:
1373
1374```js
1375nock.emitter.on('no match', req => {})
1376```
1377
1378## Nock Back
1379
1380Fixture recording support and playback.
1381
1382### Setup
1383
1384You must specify a fixture directory before using, for example:
1385
1386In your test helper
1387
1388```js
1389const nockBack = require('nock').back
1390
1391nockBack.fixtures = '/path/to/fixtures/'
1392nockBack.setMode('record')
1393```
1394
1395#### Options
1396
1397- `nockBack.fixtures` : path to fixture directory
1398- `nockBack.setMode()` : the mode to use
1399
1400### Usage
1401
1402By default if the fixture doesn't exist, a `nockBack` will create a new fixture and save the recorded output
1403for you. The next time you run the test, if the fixture exists, it will be loaded in.
1404
1405The `this` context of the callback function will have a property `scopes` to access all of the loaded
1406nock scopes.
1407
1408```js
1409const nockBack = require('nock').back
1410const request = require('request')
1411nockBack.setMode('record')
1412
1413nockBack.fixtures = __dirname + '/nockFixtures' //this only needs to be set once in your test helper
1414
1415// recording of the fixture
1416nockBack('zomboFixture.json', nockDone => {
1417 request.get('http://zombo.com', (err, res, body) => {
1418 nockDone()
1419
1420 // usage of the created fixture
1421 nockBack('zomboFixture.json', function(nockDone) {
1422 http.get('http://zombo.com/').end() // respond body "Ok"
1423
1424 this.assertScopesFinished() //throws an exception if all nocks in fixture were not satisfied
1425 http.get('http://zombo.com/').end() // throws exception because someFixture.json only had one call
1426
1427 nockDone() //never gets here
1428 })
1429 })
1430})
1431```
1432
1433If your tests are using promises then use `nockBack` like this:
1434
1435```
1436return nockBack('promisedFixture.json')
1437 .then(({ nockDone, context }) => {
1438 // do your tests returning a promise and chain it with
1439 // `.then(nockDone)`
1440 })
1441})
1442```
1443
1444#### Options
1445
1446As an optional second parameter you can pass the following options
1447
1448- `before`: a preprocessing function, gets called before nock.define
1449- `after`: a postprocessing function, gets called after nock.define
1450- `afterRecord`: a postprocessing function, gets called after recording. Is passed the array of scopes recorded and should return the intact array, a modified version of the array, or if custom formatting is desired, a stringified version of the array to save to the fixture
1451- `recorder`: custom options to pass to the recorder
1452
1453##### Example
1454
1455```js
1456function prepareScope(scope) {
1457 scope.filteringRequestBody = (body, aRecordedBody) => {
1458 if (typeof(body) !== 'string' || typeof(aRecordedBody) !== 'string') {
1459 return body
1460 }
1461
1462 const recordedBodyResult = /timestamp:([0-9]+)/.exec(aRecordedBody)
1463 if (recordedBodyResult) {
1464 const recordedTimestamp = recordedBodyResult[1]
1465 return body.replace(
1466 /(timestamp):([0-9]+)/g,
1467 (match, key, value) => `${key}:${recordedTimestamp}`
1468 )
1469 } else {
1470 return body
1471 }
1472 }
1473}
1474
1475nockBack('zomboFixture.json', { before: prepareScope }, nockDone => {
1476 request.get('http://zombo.com', function(err, res, body) {
1477 // do your tests
1478 nockDone()
1479 }
1480}
1481```
1482
1483#### Modes
1484
1485To set the mode call `nockBack.setMode(mode)` or run the tests with the `NOCK_BACK_MODE` environment variable set before loading nock. If the mode needs to be changed programmatically, the following is valid: `nockBack.setMode(nockBack.currentMode)`
1486
1487- wild: all requests go out to the internet, don't replay anything, doesn't record anything
1488
1489- dryrun: The default, use recorded nocks, allow http calls, doesn't record anything, useful for writing new tests
1490
1491- record: use recorded nocks, record new nocks
1492
1493- lockdown: use recorded nocks, disables all http calls even when not nocked, doesn't record
1494
1495## Common issues
1496
1497**"No match for response" when using got with error responses**
1498
1499[Got][] automatically retries failed requests twice. That means if you have a
1500test which mocks a 4xx or 5xx response, got will immediately reissue it. At
1501that point, the mock will have been consumed and the second request will error
1502out with **Nock: No match for request**.
1503
1504The same is true for `.replyWithError()`.
1505
1506Adding `{ retry: 0 }` to the `got` invocations will disable retrying, e.g.:
1507
1508```
1509await got("http://example.test/", { retry: 0 })
1510```
1511
1512If you need to do this in all your tests, you can create a module
1513`got_client.js` which exports a custom got instance:
1514
1515```
1516const got = require('got')
1517
1518module.exports = got.extend({ retry: 0 })
1519```
1520
1521This is how it's handled in Nock itself (see [#1523][]).
1522
1523[got]: https://github.com/sindresorhus/got
1524[#1523]: https://github.com/nock/nock/issues/1523
1525
1526### Axios
1527
1528To use Nock with [Axios][], you may need to configure Axios to use the Node
1529adapter as in the example below:
1530
1531```js
1532import axios from 'axios'
1533import nock from 'nock'
1534import test from 'ava' // You can use any test framework.
1535
1536// If you are using jsdom, axios will default to using the XHR adapter which
1537// can't be intercepted by nock. So, configure axios to use the node adapter.
1538//
1539// References:
1540// https://github.com/nock/nock/issues/699#issuecomment-272708264
1541// https://github.com/axios/axios/issues/305
1542axios.defaults.adapter = require('axios/lib/adapters/http')
1543
1544test('can fetch test response', async t => {
1545 // Set up the mock request.
1546 const scope = nock('http://localhost')
1547 .get('/test')
1548 .reply(200, 'test response')
1549
1550 // Make the request. Note that the hostname must match exactly what is passed
1551 // to `nock()`. Alternatively you can set `axios.defaults.host = 'http://localhost'`
1552 // and run `axios.get('/test')`.
1553 await axios.get('http://localhost/test')
1554
1555 // Assert that the expected request was made.
1556 scope.done()
1557})
1558```
1559
1560[axios]: https://github.com/axios/axios
1561
1562## Debugging
1563
1564Nock uses [`debug`](https://github.com/visionmedia/debug), so just run with environmental variable `DEBUG` set to `nock.*`.
1565
1566```js
1567$ DEBUG=nock.* node my_test.js
1568```
1569
1570## Contributing
1571
1572Thanks for wanting to contribute! Take a look at our [Contributing Guide](CONTRIBUTING.md) for notes on our commit message conventions and how to run tests.
1573
1574Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md).
1575By participating in this project you agree to abide by its terms.
1576
1577## Contributors
1578
1579Thanks goes to these wonderful people ([emoji key](https://github.com/all-contributors/all-contributors#emoji-key)):
1580
1581<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
1582<!-- prettier-ignore -->
1583| [<img src="https://avatars1.githubusercontent.com/u/47910?v=4" width="100px;" alt="Pedro Teixeira"/><br /><sub><b>Pedro Teixeira</b></sub>](http://pgte.me)<br />[💻](https://github.com/nock/nock/commits?author=pgte "Code") [🚧](#maintenance-pgte "Maintenance") | [<img src="https://avatars3.githubusercontent.com/u/10771967?v=4" width="100px;" alt="n30n0v"/><br /><sub><b>n30n0v</b></sub>](https://github.com/n30n0v)<br />[💻](https://github.com/nock/nock/commits?author=n30n0v "Code") | [<img src="https://avatars3.githubusercontent.com/u/910753?v=4" width="100px;" alt="Richard Littauer"/><br /><sub><b>Richard Littauer</b></sub>](https://burntfen.com)<br />[🚧](#maintenance-RichardLitt "Maintenance") [💻](https://github.com/nock/nock/commits?author=RichardLitt "Code") [📝](#blog-RichardLitt "Blogposts") | [<img src="https://avatars1.githubusercontent.com/u/3731165?v=4" width="100px;" alt="Ian Walker-Sperber"/><br /><sub><b>Ian Walker-Sperber</b></sub>](http://ianwsperber.com)<br />[💻](https://github.com/nock/nock/commits?author=ianwsperber "Code") | [<img src="https://avatars2.githubusercontent.com/u/1505203?v=4" width="100px;" alt="Ivan Erceg"/><br /><sub><b>Ivan Erceg</b></sub>](http://ilovacha.com)<br />[💻](https://github.com/nock/nock/commits?author=ierceg "Code") [🚧](#maintenance-ierceg "Maintenance") | [<img src="https://avatars2.githubusercontent.com/u/1487036?v=4" width="100px;" alt="Paul Melnikow"/><br /><sub><b>Paul Melnikow</b></sub>](https://twitter.com/paulmelnikow)<br />[💻](https://github.com/nock/nock/commits?author=paulmelnikow "Code") [🚧](#maintenance-paulmelnikow "Maintenance") | [<img src="https://avatars3.githubusercontent.com/u/39992?v=4" width="100px;" alt="Gregor Martynus"/><br /><sub><b>Gregor Martynus</b></sub>](https://twitter.com/gr2m)<br />[💻](https://github.com/nock/nock/commits?author=gr2m "Code") [🚧](#maintenance-gr2m "Maintenance") [💼](#business-gr2m "Business development") [💵](#financial-gr2m "Financial") [📝](#blog-gr2m "Blogposts") |
1584| :---: | :---: | :---: | :---: | :---: | :---: | :---: |
1585| [<img src="https://avatars1.githubusercontent.com/u/6701030?v=4" width="100px;" alt="Hutson Betts"/><br /><sub><b>Hutson Betts</b></sub>](https://gitlab.com/hutson)<br />[💵](#financial-hutson "Financial") | [<img src="https://avatars2.githubusercontent.com/u/6105119?v=4" width="100px;" alt="Jonas Lilja"/><br /><sub><b>Jonas Lilja</b></sub>](http://lilja.io)<br />[💵](#financial-jlilja "Financial") [💻](https://github.com/nock/nock/commits?author=jlilja "Code") | [<img src="https://avatars0.githubusercontent.com/u/4446950?v=4" width="100px;" alt="Benjamin Ki"/><br /><sub><b>Benjamin Ki</b></sub>](https://github.com/benrki)<br />[💵](#financial-benrki "Financial") | [<img src="https://avatars2.githubusercontent.com/u/3250463?v=4" width="100px;" alt="Chad Fawcett"/><br /><sub><b>Chad Fawcett</b></sub>](http://chadf.ca)<br />[💵](#financial-chadfawcett "Financial") |
1586
1587<!-- ALL-CONTRIBUTORS-LIST:END -->
1588
1589This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
1590
1591## Sponsors
1592
1593Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/nock#sponsor)]
1594
1595<a href="https://opencollective.com/nock/sponsor/0/website" target="_blank"><img src="https://opencollective.com/nock/sponsor/0/avatar.svg"></a>
1596<a href="https://opencollective.com/nock/sponsor/1/website" target="_blank"><img src="https://opencollective.com/nock/sponsor/1/avatar.svg"></a>
1597<a href="https://opencollective.com/nock/sponsor/2/website" target="_blank"><img src="https://opencollective.com/nock/sponsor/2/avatar.svg"></a>
1598<a href="https://opencollective.com/nock/sponsor/3/website" target="_blank"><img src="https://opencollective.com/nock/sponsor/3/avatar.svg"></a>
1599<a href="https://opencollective.com/nock/sponsor/4/website" target="_blank"><img src="https://opencollective.com/nock/sponsor/4/avatar.svg"></a>
1600<a href="https://opencollective.com/nock/sponsor/5/website" target="_blank"><img src="https://opencollective.com/nock/sponsor/5/avatar.svg"></a>
1601<a href="https://opencollective.com/nock/sponsor/6/website" target="_blank"><img src="https://opencollective.com/nock/sponsor/6/avatar.svg"></a>
1602<a href="https://opencollective.com/nock/sponsor/7/website" target="_blank"><img src="https://opencollective.com/nock/sponsor/7/avatar.svg"></a>
1603<a href="https://opencollective.com/nock/sponsor/8/website" target="_blank"><img src="https://opencollective.com/nock/sponsor/8/avatar.svg"></a>
1604<a href="https://opencollective.com/nock/sponsor/9/website" target="_blank"><img src="https://opencollective.com/nock/sponsor/9/avatar.svg"></a>
1605
1606## License
1607
1608[MIT](LICENSE)
1609
1610Copyright (c) 2011–2019 [Pedro Teixeira](http://about.me/pedroteixeira) and other [contributors](https://github.com/nock/nock/graphs/contributors).