UNPKG

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