nock 9.6.1 → 10.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,26 @@
1
+ ---
2
+ name: 🐛 Bug report
3
+ about: If something isn't working 🤕
4
+
5
+ ---
6
+
7
+ **What is the expected behavior?**
8
+
9
+ **What is the actual behavior?**
10
+
11
+ **Possible solution**
12
+
13
+ **How to reproduce the issue**
14
+
15
+ Runkit: *[Example link](https://runkit.com/gr2m/node-nock-nock-768)*
16
+
17
+ _Having problem producing a test case? Try and ask the community for help. If the test case cannot be reproduced, the Nock community might not be able to help you._
18
+
19
+ **Does the bug have a test case?**
20
+
21
+ **Versions**
22
+
23
+ | Software | Version(s) |
24
+ |----------|------------|
25
+ | Nock | |
26
+ | Node | |
@@ -0,0 +1,21 @@
1
+ ---
2
+ name: 🚀 Feature request
3
+ about: Let us know if you have a feature request 💡
4
+
5
+ ---
6
+
7
+ **Context**
8
+
9
+ What are you trying to do and how would you want to do it differently? Is it something you currently you cannot do? Is this related to an issue/problem?
10
+
11
+ **Alternatives**
12
+
13
+ Can you achieve the same result doing it in an alternative way? Is the alternative considerable?
14
+
15
+ **Has the feature been requested before?**
16
+
17
+ Please provide a link to the issue.
18
+
19
+ **If the feature request is accepted, would you be willing to submit a PR?**
20
+
21
+ Yes / No _(Help can be provided if you need assistance submitting a PR)_
@@ -0,0 +1,24 @@
1
+ ---
2
+ name: ❓ Support
3
+ about: If you need support, check out Nock on StackOverflow
4
+
5
+ ---
6
+
7
+ <!-- 👆 Click "Preview" for a nicer view! -->
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+ We primarily use GitHub as an issue tracker; for usage and support questions we primairly use StackOverflow. Please tag the questions with `nock` so the community can easily find it. [Go to StackOverflow](https://stackoverflow.com/questions/tagged/nock).
23
+
24
+ If you want to submit a feature request you can do that [here](https://github.com/nock/nock/issues/new?template=feature_request.md) or bug reports [here](https://github.com/nock/nock/issues/new?template=bug_report.md).
@@ -0,0 +1,21 @@
1
+ ---
2
+ name: ❤️ Say thank you
3
+ about: Tell us how you use nock & support our efforts in maintaining Nock
4
+
5
+ ---
6
+
7
+ # ❤️ I'm using Nock
8
+
9
+ If you (or your company) are using Nock - please let us know. We'd love to hear from you!
10
+
11
+ Nock is a community driven project, which means it's not maintained by a company. If you would like to help Nock - any of the following is greatly appreciated.
12
+
13
+ - [ ] Give the repository a star ⭐️
14
+ - [ ] Help out with issues
15
+ - [ ] Review pull requests
16
+ - [ ] Blog about Nock
17
+ - [ ] Make tutorials
18
+ - [ ] Give talks
19
+ - [ ] Support us on [https://opencollective.com/nock](https://opencollective.com/nock)
20
+
21
+ Thank you! 💐
@@ -0,0 +1,19 @@
1
+ # Configuration for lock-threads - https://github.com/dessant/lock-threads
2
+
3
+ # Number of days of inactivity before a closed issue or pull request is locked
4
+ daysUntilLock: 14
5
+
6
+ # Issues and pull requests with these labels will not be locked. Set to `[]` to disable
7
+ exemptLabels: []
8
+
9
+ # Label to add before locking, such as `outdated`. Set to `false` to disable
10
+ lockLabel: false
11
+
12
+ # Comment to post before locking. Set to `false` to disable
13
+ lockComment: >
14
+ This thread has been automatically locked since there has not been
15
+ any recent activity after it was closed. Please open a new issue and
16
+ add a reference to this one if it’s related. Thank you!
17
+
18
+ # Assign `resolved` as the reason for locking. Set to `false` to disable
19
+ setLockReason: true
@@ -0,0 +1,25 @@
1
+ # Configuration for probot-stale - https://github.com/probot/stale
2
+
3
+ # Number of days of inactivity before an Issue or Pull Request becomes stale
4
+ daysUntilStale: 90
5
+
6
+ # Number of days of inactivity before an Issue or Pull Request with the stale label is closed.
7
+ # Set to false to disable. If disabled, issues still need to be closed manually, but will remain marked as stale.
8
+ daysUntilClose: 7
9
+
10
+ # Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable
11
+ exemptLabels:
12
+ - pinned
13
+
14
+ # Label to use when marking as stale
15
+ staleLabel: stale
16
+
17
+ # Comment to post when marking as stale. Set to `false` to disable
18
+ markComment: >
19
+ This issue has been automatically marked as stale because it has not had
20
+ recent activity. It will be closed if no further activity occurs. We try to
21
+ do our best, but nock is maintained by volunteers and there is only so much
22
+ we can do at a time. Thank you for your contributions.
23
+
24
+ # Limit the number of actions per hour, from 1-30. Default is 30
25
+ limitPerRun: 30
package/.travis.yml CHANGED
@@ -23,14 +23,12 @@ jobs:
23
23
  env: linting
24
24
  script: npm run lint
25
25
  - stage: test
26
- node_js: 9
26
+ node_js: 10
27
27
  script: npm run unit
28
28
  - node_js: 8
29
29
  script: npm run unit
30
30
  - node_js: 6
31
31
  script: npm run unit
32
- - node_js: 4
33
- script: npm run unit
34
32
  - stage: release
35
33
  node_js: lts/*
36
34
  env: semantic-release
@@ -38,5 +36,5 @@ jobs:
38
36
  - node_js: lts/*
39
37
  env: coverage
40
38
  script:
41
- - npm run coverage
42
- - npm run coveralls
39
+ - npm run test
40
+ - npm run coverage:upload
package/CONTRIBUTING.md CHANGED
@@ -12,6 +12,8 @@ Please note that this project is released with a [Contributor Code of Conduct](.
12
12
  - [Generate README TOC](#generate-readme-toc)
13
13
  - [Running tests](#running-tests)
14
14
  * [Airplane mode](#airplane-mode)
15
+ - [Release Process](#release-process)
16
+ - [GitHub Apps](#github-apps)
15
17
  - [Becoming a maintainer](#becoming-a-maintainer)
16
18
 
17
19
  <!-- tocstop -->
@@ -60,6 +62,18 @@ $ export AIRPLANE=true
60
62
  $ npm test
61
63
  ```
62
64
 
65
+ ## Release Process
66
+
67
+ All of our releases are automated using [semantic-release](https://github.com/semantic-release/semantic-release). The commit messages pushed to the master branch trigger new releases. Semantic-release requires that commits follow certain conventions, [described above](#commit-message-conventions). semantic-release creates a GitHub release, adds release notes and publishes the new version to npm. This is why we do not store release notes in the [`CHANGELOG`](CHANGELOG.md) file - they're already on GitHub.
68
+
69
+ We use @nockbot as a separate account for releases, because npm tokens cannot be scoped to a single package. This improves our security model in case of a data breach involving npm tokens. @nockbot's credentials were set up by @gr2m; contact him if for any reason you need to change this in the future.
70
+
71
+ ## GitHub Apps
72
+
73
+ We use several GitHub apps to help maintain this repository. While we would like to address every issue and while we would like to be on hand to support every person, Nock is pretty much entirely volunteer run, and we simply don't have the time to do everything. Please don't be offended if an automated app posts in your issue! We're doing what we can with with we have.
74
+
75
+ Currently, we use the [Stale](https://github.com/apps/stale) and [Lock](https://github.com/apps/lock) apps to mark old issues as stale, and to lock issues which have been closed to stop drive-by comments. You can see the configuration files for these in [.github/](.github).
76
+
63
77
  ## Becoming a maintainer
64
78
 
65
79
  So you want to do more than file a bug or submit a PR? Awesome!
@@ -76,3 +90,22 @@ Here are some things you can do today to actively show the Nock team that you're
76
90
  * **Refactor.** This is one of the hardest things to do, but one of the most useful. Go through the code, and find examples where it could be written better - with better variable names, more useful abstractions, and more elegant patterns. Taking away ten lines of code that are unnecessary is more valuable than submitting a hundred new lines, sometimes. Open a PR or a comment and defend your position; ask for feedback.
77
91
 
78
92
  Once you've been around for a bit, ask a current Maintainer - one of [the team members](https://github.com/orgs/nock/people) - whether you can be elevated to Maintainer status and given permissions to close issues and merge PRs. We're interested in how well you know what Nock is about, and how involved you are in the community - not where you're from, how good your English is, or whether or not you can pass a whiteboard test blindfolded. If you think that you've been helpful, let us know. We're friendly, promise. :)
93
+
94
+ ## Generating the CONTRIBUTORS.md file
95
+
96
+ We use [`name-your-contributors`](https://github.com/mntnr/name-your-contributors) to generate the CONTRIBUTORS file, which contains the names of everyone who have submitted code to the Nock codebase, or commented on an issue, or opened a pull request, or reviewed anyone else's code. After all, all contributions are welcome, and anyone who works with Nock is part of our community.
97
+
98
+ To generate this file, download `name-your-contributors` and set up a GitHub authorization token.
99
+
100
+ ```sh
101
+ # Generate a JSON file of the members. This may take a while.
102
+ $ name-your-contributors -r nock -u nock > contributors.json
103
+ ```
104
+
105
+ To parse that file, we suggest using [`jq`](https://stedolan.github.io/jq/), although other options are clearly possible:
106
+
107
+ ```sh
108
+ cat contribs.json | jq '.[][]' | jq '"\(if (.name | length) > 0 then .name else null end) @\(.login) \(.url)"' | jq '. | tostring' | jq -s . | jq unique | jq .[] > CONTRIBUTORS.md
109
+ ```
110
+
111
+ Note: This is a convoluted and time-intensive process, and could be updated in several ways. For one, `name-your-contributors` accepts a date flag, which could be used to only catch recent entries. Another way would be to use a bot to automate this at some regular interval. Any help on this would be appreciated.
package/README.md CHANGED
@@ -3,6 +3,8 @@
3
3
  [![Build Status](https://travis-ci.org/nock/nock.svg?branch=master)](https://travis-ci.org/nock/nock)
4
4
  [![Coverage Status](https://coveralls.io/repos/github/nock/nock/badge.svg?branch=master)](https://coveralls.io/github/nock/nock?branch=master)
5
5
  [![Greenkeeper](https://badges.greenkeeper.io/nock/nock.svg)](https://greenkeeper.io/)
6
+ [![Backers on Open Collective](https://opencollective.com/nock/backers/badge.svg)](#backers)
7
+ [![Sponsors on Open Collective](https://opencollective.com/nock/sponsors/badge.svg)](#sponsors)
6
8
 
7
9
  > HTTP server mocking and expectations library for Node.js
8
10
 
@@ -47,7 +49,7 @@ For instance, if a module performs HTTP requests to a CouchDB server or makes HT
47
49
  * [Request Body filtering](#request-body-filtering)
48
50
  * [Request Headers Matching](#request-headers-matching)
49
51
  * [Optional Requests](#optional-requests)
50
- * [Allow __unmocked__ requests on a mocked hostname](#allow-__unmocked__-requests-on-a-mocked-hostname)
52
+ * [Allow __unmocked__ requests on a mocked hostname](#allow-unmocked-requests-on-a-mocked-hostname)
51
53
  - [Expectations](#expectations)
52
54
  * [.isDone()](#isdone)
53
55
  * [.cleanAll()](#cleanall)
@@ -59,7 +61,10 @@ For instance, if a module performs HTTP requests to a CouchDB server or makes HT
59
61
  - [Restoring](#restoring)
60
62
  - [Activating](#activating)
61
63
  - [Turning Nock Off (experimental!)](#turning-nock-off-experimental)
62
- - [Enable/Disable real HTTP request](#enabledisable-real-http-request)
64
+ - [Enable/Disable real HTTP requests](#enabledisable-real-http-requests)
65
+ * [Disabling requests](#disabling-requests)
66
+ * [Enabling requests](#enabling-requests)
67
+ * [Resetting NetConnect](#resetting-netconnect)
63
68
  - [Recording](#recording)
64
69
  * [`dont_print` option](#dont_print-option)
65
70
  * [`output_objects` option](#output_objects-option)
@@ -76,8 +81,9 @@ For instance, if a module performs HTTP requests to a CouchDB server or makes HT
76
81
  + [Options](#options-1)
77
82
  + [Modes](#modes)
78
83
  - [Debugging](#debugging)
79
- - [PROTIP](#protip)
80
84
  - [Contributing](#contributing)
85
+ - [Backers](#backers)
86
+ - [Sponsors](#sponsors)
81
87
  - [License](#license)
82
88
 
83
89
  <!-- tocstop -->
@@ -94,14 +100,19 @@ $ npm install --save nock
94
100
 
95
101
  ### Node version support
96
102
 
103
+ The latest version of nock supports all currently maintained Node versions, see [Node Release Schedule](https://github.com/nodejs/Release#release-schedule)
104
+
105
+ Here is a list of past nock versions with respective node version support
106
+
97
107
  | node | nock |
98
108
  |---|---|
99
109
  | 0.10 | up to 8.x |
100
110
  | 0.11 | up to 8.x |
101
111
  | 0.12 | up to 8.x |
102
- | 4 | 9.x |
112
+ | 4 | up to 9.x |
103
113
  | 5 | up to 8.x |
104
- | 6 | 9.x |
114
+ | 7 | up to 9.x |
115
+ | 9 | up to 9.x |
105
116
 
106
117
  ## Usage
107
118
 
@@ -221,7 +232,7 @@ nock('http://www.example.com')
221
232
 
222
233
  ```js
223
234
  nock('http://www.example.com')
224
- .post('/login', function(body) {
235
+ .post('/login', function(body) {
225
236
  return body.username && body.password;
226
237
  })
227
238
  .reply(200, { id: '123ABC' });
@@ -629,7 +640,7 @@ nock('http://my.server.com')
629
640
  .reply(200, '<html></html>')
630
641
  ```
631
642
 
632
- NOTE: the [`'response'`](http://nodejs.org/api/http.html#http_event_response) event will occur immediately, but the [IncomingMessage](http://nodejs.org/api/http.html#http_http_incomingmessage) will not emit it's `'end'` event until after the delay.
643
+ NOTE: 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.
633
644
 
634
645
  ### Delay the response
635
646
 
@@ -788,6 +799,17 @@ var scope = nock('http://api.myservice.com')
788
799
  .reply(201, 'OK');
789
800
  ```
790
801
 
802
+ If you don't want to match the request body you can return a wildcard match:
803
+
804
+ ```js
805
+ var scope = nock('http://api.myservice.com')
806
+ .filteringRequestBody(function(body) {
807
+ return '*';
808
+ })
809
+ .post('/some_uri', '*')
810
+ .reply(200, 'OK');
811
+ ```
812
+
791
813
  ### Request Headers Matching
792
814
 
793
815
  If you need to match requests only if certain request headers match, you can.
@@ -1009,7 +1031,7 @@ Only for cases where nock has been deactivated using [nock.restore()](#restoring
1009
1031
  nock.activate();
1010
1032
  ```
1011
1033
 
1012
- **note**: To check if nock HTTP interceptor is active or deactive, use [nock.isActive()](#isactive).
1034
+ **note**: To check if nock HTTP interceptor is active or inactive, use [nock.isActive()](#isactive).
1013
1035
 
1014
1036
  ## Turning Nock Off (experimental!)
1015
1037
 
@@ -1021,17 +1043,19 @@ This way you can have your tests hit the real servers just by switching on this
1021
1043
  $ NOCK_OFF=true node my_test.js
1022
1044
  ```
1023
1045
 
1024
- ## Enable/Disable real HTTP request
1046
+ ## Enable/Disable real HTTP requests
1025
1047
 
1026
1048
  By 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.
1027
1049
 
1050
+ ### Disabling requests
1051
+
1028
1052
  For disabling real http requests.
1029
1053
 
1030
1054
  ```js
1031
1055
  nock.disableNetConnect();
1032
1056
  ```
1033
1057
 
1034
- So, if you try to request any host not 'nocked', it will thrown an `NetConnectNotAllowedError`.
1058
+ So, if you try to request any host not 'nocked', it will throw a `NetConnectNotAllowedError`.
1035
1059
 
1036
1060
  ```js
1037
1061
  nock.disableNetConnect();
@@ -1041,40 +1065,45 @@ req.on('error', function(err){
1041
1065
  });
1042
1066
  // The returned `http.ClientRequest` will emit an error event (or throw if you're not listening for it)
1043
1067
  // This code will log a NetConnectNotAllowedError with message:
1044
- // Nock: Not allow net connect for "google.com:80"
1068
+ // Nock: Disallowed net connect for "google.com:80"
1045
1069
  ```
1046
1070
 
1047
- For enabling real HTTP requests (the default behaviour).
1071
+ ### Enabling requests
1072
+
1073
+ For enabling any real HTTP requests (the default behavior):
1048
1074
 
1049
1075
  ```js
1050
1076
  nock.enableNetConnect();
1051
1077
  ```
1052
1078
 
1053
- You could allow real HTTP request for certain host names by providing a string or a regular expression for the hostname:
1079
+ You could allow real HTTP requests for certain host names by providing a string or a regular expression for the hostname:
1054
1080
 
1055
1081
  ```js
1056
- // using a string
1082
+ // Using a string
1057
1083
  nock.enableNetConnect('amazon.com');
1058
1084
 
1059
- // or a RegExp
1060
- nock.enableNetConnect(/(amazon|github).com/);
1085
+ // Or a RegExp
1086
+ nock.enableNetConnect(/(amazon|github)\.com/);
1061
1087
 
1062
1088
  http.get('http://www.amazon.com/');
1063
- http.get('http://github.com/'); // only for second example
1089
+ http.get('http://github.com/');
1064
1090
 
1065
- // This request will be done!
1066
1091
  http.get('http://google.com/');
1067
- // this will throw NetConnectNotAllowedError with message:
1068
- // Nock: Not allow net connect for "google.com:80"
1092
+ // This will throw NetConnectNotAllowedError with message:
1093
+ // Nock: Disallowed net connect for "google.com:80"
1069
1094
  ```
1070
1095
 
1071
- A common use case when testing local endpoints would be to disable all but local host, then adding in additional nocks for external requests:
1096
+ A common use case when testing local endpoints would be to disable all but localhost, then add in additional nocks for external requests:
1072
1097
 
1073
1098
  ```js
1074
1099
  nock.disableNetConnect();
1075
- nock.enableNetConnect('127.0.0.1'); //Allow localhost connections so we can test local routes and mock servers.
1100
+ // Allow localhost connections so we can test local routes and mock servers.
1101
+ nock.enableNetConnect('127.0.0.1');
1076
1102
  ```
1077
- Then when you're done with the test, you probably want to set everything back to normal:
1103
+
1104
+ ### Resetting NetConnect
1105
+
1106
+ When you're done with the test, you probably want to set everything back to normal:
1078
1107
 
1079
1108
  ```js
1080
1109
  nock.cleanAll();
@@ -1115,7 +1144,7 @@ var nockCalls = nock.recorder.play();
1115
1144
 
1116
1145
  The `nockCalls` var will contain an array of strings representing the generated code you need.
1117
1146
 
1118
- Copy and paste that code into your tests, customize at will, and you're done! You can call `nock.recorder.reset()` to remove already recorded calls from the array that `nock.recorder.play()` returns.
1147
+ Copy 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.
1119
1148
 
1120
1149
  (Remember that you should do this one test at a time).
1121
1150
 
@@ -1184,7 +1213,7 @@ var nocks = nock.define(nockDefs);
1184
1213
 
1185
1214
  ### `enable_reqheaders_recording` option
1186
1215
 
1187
- Recording request headers by default is deemed more trouble than its worth as some of them depend on the timestamp or other values that may change after the tests have been recorder thus leading to complex postprocessing of recorded tests. Thus by default the request headers are not recorded.
1216
+ Recording 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 recorder thus leading to complex postprocessing of recorded tests. Thus by default the request headers are not recorded.
1188
1217
 
1189
1218
  The 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.
1190
1219
 
@@ -1213,7 +1242,7 @@ nock.recorder.rec({
1213
1242
 
1214
1243
  ### `use_separator` option
1215
1244
 
1216
- By default, nock will wrap it's output with the separator string `<<<<<<-- cut here -->>>>>>` before and after anything it prints, whether to the console or a custom log function given with the `logging` option.
1245
+ By 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.
1217
1246
 
1218
1247
  To disable this, set `use_separator` to false.
1219
1248
 
@@ -1268,11 +1297,11 @@ nock.emitter.on('no match', function(req) {
1268
1297
 
1269
1298
  ## Nock Back
1270
1299
 
1271
- fixture recording support and playback
1300
+ Fixture recording support and playback.
1272
1301
 
1273
1302
  ### Setup
1274
1303
 
1275
- **You must specify a fixture directory before using, for example:
1304
+ You must specify a fixture directory before using, for example:
1276
1305
 
1277
1306
  In your test helper
1278
1307
 
@@ -1304,24 +1333,6 @@ nockBack.setMode('record');
1304
1333
 
1305
1334
  nockBack.fixtures = __dirname + '/nockFixtures'; //this only needs to be set once in your test helper
1306
1335
 
1307
- var before = function(scope) {
1308
- scope.filteringRequestBody = function(body, aRecordedBody) {
1309
- if (typeof(body) !== 'string' || typeof(aRecordedBody) !== 'string') {
1310
- return body;
1311
- }
1312
-
1313
- var recordedBodyResult = /timestamp:([0-9]+)/.exec(aRecordedBody);
1314
- if (!recordedBodyResult) {
1315
- return body;
1316
- }
1317
-
1318
- var recordedTimestamp = recordedBodyResult[1];
1319
- return body.replace(/(timestamp):([0-9]+)/g, function(match, key, value) {
1320
- return key + ':' + recordedTimestamp;
1321
- });
1322
- };
1323
- }
1324
-
1325
1336
  // recording of the fixture
1326
1337
  nockBack('zomboFixture.json', function(nockDone) {
1327
1338
  request.get('http://zombo.com', function(err, res, body) {
@@ -1361,10 +1372,38 @@ As an optional second parameter you can pass the following options
1361
1372
  - `afterRecord`: a postprocessing function, gets called after recording. Is passed the array of scopes recorded and should return the array scopes to save to the fixture
1362
1373
  - `recorder`: custom options to pass to the recorder
1363
1374
 
1375
+ ##### Example
1376
+
1377
+ ```javascript
1378
+ var beforeFunc = function(scope) {
1379
+ scope.filteringRequestBody = function(body, aRecordedBody) {
1380
+ if (typeof(body) !== 'string' || typeof(aRecordedBody) !== 'string') {
1381
+ return body;
1382
+ }
1383
+
1384
+ var recordedBodyResult = /timestamp:([0-9]+)/.exec(aRecordedBody);
1385
+ if (!recordedBodyResult) {
1386
+ return body;
1387
+ }
1388
+
1389
+ var recordedTimestamp = recordedBodyResult[1];
1390
+ return body.replace(/(timestamp):([0-9]+)/g, function(match, key, value) {
1391
+ return key + ':' + recordedTimestamp;
1392
+ });
1393
+ };
1394
+ }
1395
+
1396
+ nockBack('zomboFixture.json', { before: beforeFunc }, function(nockDone) {
1397
+ request.get('http://zombo.com', function(err, res, body) {
1398
+ // do your tests
1399
+ nockDone();
1400
+ }
1401
+ }
1402
+ ```
1364
1403
 
1365
1404
  #### Modes
1366
1405
 
1367
- to set the mode call `nockBack.setMode(mode)` or run the tests with the `NOCK_BACK_MODE` environment variable set before loading nock. If the mode needs to be changed programatically, the following is valid: `nockBack.setMode(nockBack.currentMode)`
1406
+ To 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)`
1368
1407
 
1369
1408
  - wild: all requests go out to the internet, don't replay anything, doesn't record anything
1370
1409
 
@@ -1375,32 +1414,41 @@ to set the mode call `nockBack.setMode(mode)` or run the tests with the `NOCK_BA
1375
1414
  - lockdown: use recorded nocks, disables all http calls even when not nocked, doesn't record
1376
1415
 
1377
1416
  ## Debugging
1378
- Nock uses debug, so just run with environmental variable DEBUG set to nock.*
1379
1417
 
1380
- ```js
1381
- $ DEBUG=nock.* node my_test.js
1382
- ```
1383
-
1384
- ## PROTIP
1385
-
1386
- If you don't want to match the request body you can use this trick (by @theycallmeswift):
1418
+ Nock uses [`debug`](https://github.com/visionmedia/debug), so just run with environmental variable `DEBUG` set to `nock.*`.
1387
1419
 
1388
1420
  ```js
1389
- var scope = nock('http://api.myservice.com')
1390
- .filteringRequestBody(function(body) {
1391
- return '*';
1392
- })
1393
- .post('/some_uri', '*')
1394
- .reply(200, 'OK');
1421
+ $ DEBUG=nock.* node my_test.js
1395
1422
  ```
1396
1423
 
1397
1424
  ## Contributing
1398
1425
 
1399
1426
  Thanks 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.
1400
1427
 
1401
- Please note that this project is released with a [Contributor Code of Conduct](./CODE_OF_CONDUCT.md).
1428
+ Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md).
1402
1429
  By participating in this project you agree to abide by its terms.
1403
1430
 
1431
+ ## Backers
1432
+
1433
+ Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/nock#backer)]
1434
+
1435
+ <a href="https://opencollective.com/nock#backers" target="_blank"><img src="https://opencollective.com/nock/backers.svg?width=890"></a>
1436
+
1437
+ ## Sponsors
1438
+
1439
+ Support 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)]
1440
+
1441
+ <a href="https://opencollective.com/nock/sponsor/0/website" target="_blank"><img src="https://opencollective.com/nock/sponsor/0/avatar.svg"></a>
1442
+ <a href="https://opencollective.com/nock/sponsor/1/website" target="_blank"><img src="https://opencollective.com/nock/sponsor/1/avatar.svg"></a>
1443
+ <a href="https://opencollective.com/nock/sponsor/2/website" target="_blank"><img src="https://opencollective.com/nock/sponsor/2/avatar.svg"></a>
1444
+ <a href="https://opencollective.com/nock/sponsor/3/website" target="_blank"><img src="https://opencollective.com/nock/sponsor/3/avatar.svg"></a>
1445
+ <a href="https://opencollective.com/nock/sponsor/4/website" target="_blank"><img src="https://opencollective.com/nock/sponsor/4/avatar.svg"></a>
1446
+ <a href="https://opencollective.com/nock/sponsor/5/website" target="_blank"><img src="https://opencollective.com/nock/sponsor/5/avatar.svg"></a>
1447
+ <a href="https://opencollective.com/nock/sponsor/6/website" target="_blank"><img src="https://opencollective.com/nock/sponsor/6/avatar.svg"></a>
1448
+ <a href="https://opencollective.com/nock/sponsor/7/website" target="_blank"><img src="https://opencollective.com/nock/sponsor/7/avatar.svg"></a>
1449
+ <a href="https://opencollective.com/nock/sponsor/8/website" target="_blank"><img src="https://opencollective.com/nock/sponsor/8/avatar.svg"></a>
1450
+ <a href="https://opencollective.com/nock/sponsor/9/website" target="_blank"><img src="https://opencollective.com/nock/sponsor/9/avatar.svg"></a>
1451
+
1404
1452
  ## License
1405
1453
 
1406
1454
  [MIT](LICENSE)
package/lib/common.js CHANGED
@@ -50,7 +50,7 @@ var isBinaryBuffer = function(buffer) {
50
50
 
51
51
  // Test if the buffer can be reconstructed verbatim from its utf8 encoding.
52
52
  var utfEncodedBuffer = buffer.toString('utf8');
53
- var reconstructedBuffer = new Buffer(utfEncodedBuffer, 'utf8');
53
+ var reconstructedBuffer = Buffer.from(utfEncodedBuffer, 'utf8');
54
54
  var compareBuffers = function(lhs, rhs) {
55
55
  if(lhs.length !== rhs.length) {
56
56
  return false;
@@ -80,7 +80,7 @@ var isBinaryBuffer = function(buffer) {
80
80
  var mergeChunks = function(chunks) {
81
81
 
82
82
  if(_.isEmpty(chunks)) {
83
- return new Buffer(0);
83
+ return Buffer.alloc(0);
84
84
  }
85
85
 
86
86
  // We assume that all chunks are Buffer objects if the first is buffer object.
package/lib/intercept.js CHANGED
@@ -33,7 +33,7 @@ function NetConnectNotAllowedError(host, path) {
33
33
 
34
34
  this.name = 'NetConnectNotAllowedError';
35
35
  this.code = 'ENETUNREACH'
36
- this.message = 'Nock: Not allow net connect for "' + host + path + '"';
36
+ this.message = 'Nock: Disallowed net connect for "' + host + path + '"';
37
37
 
38
38
  Error.captureStackTrace(this, this.constructor);
39
39
  }
@@ -405,7 +405,7 @@ Interceptor.prototype.basicAuth = function basicAuth(options) {
405
405
  var username = options['user'];
406
406
  var password = options['pass'] || '';
407
407
  var name = 'authorization';
408
- var value = 'Basic ' + new Buffer(username + ':' + password).toString('base64');
408
+ var value = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');
409
409
  this.interceptorMatchHeaders.push({ name: name, value: value });
410
410
  return this;
411
411
  };
package/lib/match_body.js CHANGED
@@ -10,12 +10,19 @@ function matchBody(spec, body) {
10
10
  if (typeof spec === 'undefined') {
11
11
  return true;
12
12
  }
13
+
13
14
  var options = this || {};
14
15
 
15
16
  if (Buffer.isBuffer(body)) {
16
17
  body = body.toString();
17
18
  }
18
19
 
20
+ if (spec instanceof RegExp) {
21
+ if (typeof body === "string") {
22
+ return body.match(spec);
23
+ }
24
+ }
25
+
19
26
  if (Buffer.isBuffer(spec)) {
20
27
  if (common.isBinaryBuffer(spec)) {
21
28
  spec = spec.toString('hex');
@@ -54,14 +61,6 @@ function matchBody(spec, body) {
54
61
  body = body.replace(/\r?\n|\r/g, '');
55
62
  }
56
63
 
57
- if (spec instanceof RegExp) {
58
- if (typeof body === "string") {
59
- return body.match(spec);
60
- } else {
61
- return qs.stringify(body).match(spec);
62
- }
63
- }
64
-
65
64
  if (!isMultipart && typeof spec === "string") {
66
65
  spec = spec.replace(/\r?\n|\r/g, '');
67
66
  }
package/lib/recorder.js CHANGED
@@ -56,7 +56,7 @@ var getBodyFromChunks = function(chunks, headers) {
56
56
  body: _.map(chunks, function(chunk) {
57
57
  if(!Buffer.isBuffer(chunk)) {
58
58
  if (typeof chunk === 'string') {
59
- chunk = new Buffer(chunk);
59
+ chunk = Buffer.from(chunk);
60
60
  } else {
61
61
  throw new Error('content-encoded responses must all be binary buffers');
62
62
  }
@@ -330,7 +330,7 @@ function record(rec_options) {
330
330
  res.push = function(data) {
331
331
  if (data) {
332
332
  if (encoding) {
333
- data = new Buffer(data, encoding);
333
+ data = Buffer.from(data, encoding);
334
334
  }
335
335
  dataChunks.push(data);
336
336
  }
@@ -358,7 +358,7 @@ function record(rec_options) {
358
358
  if (data) {
359
359
  debug(thisRecordingId, 'new', proto, 'body chunk');
360
360
  if (! Buffer.isBuffer(data)) {
361
- data = new Buffer(data, encoding);
361
+ data = Buffer.from(data, encoding);
362
362
  }
363
363
  bodyChunks.push(data);
364
364
  }
@@ -373,7 +373,7 @@ function record(rec_options) {
373
373
  if (data) {
374
374
  debug(thisRecordingId, 'new', proto, 'body chunk');
375
375
  if (! Buffer.isBuffer(data)) {
376
- data = new Buffer(data, encoding);
376
+ data = Buffer.from(data, encoding);
377
377
  }
378
378
  bodyChunks.push(data);
379
379
  }
@@ -111,7 +111,7 @@ function RequestOverrider(req, options, interceptors, remove, cb) {
111
111
 
112
112
  /// options.auth
113
113
  if (options.auth && (! options.headers || ! options.headers.authorization)) {
114
- setHeader(req, 'Authorization', 'Basic ' + (new Buffer(options.auth)).toString('base64'));
114
+ setHeader(req, 'Authorization', 'Basic ' + (Buffer.from(options.auth)).toString('base64'));
115
115
  }
116
116
 
117
117
  if (! req.connection) {
@@ -131,7 +131,7 @@ function RequestOverrider(req, options, interceptors, remove, cb) {
131
131
  if (!req.aborted) {
132
132
  if (buffer) {
133
133
  if (!Buffer.isBuffer(buffer)) {
134
- buffer = new Buffer(buffer, encoding);
134
+ buffer = Buffer.from(buffer, encoding);
135
135
  }
136
136
  requestBodyBuffers.push(buffer);
137
137
  }
@@ -318,13 +318,13 @@ function RequestOverrider(req, options, interceptors, remove, cb) {
318
318
  emitError(new Error('Gzip encoding is currently not supported in this version of Node.'));
319
319
  return;
320
320
  }
321
- requestBody = String(zlib.gunzipSync(new Buffer(requestBody, 'hex')), 'hex')
321
+ requestBody = String(zlib.gunzipSync(Buffer.from(requestBody, 'hex')), 'hex')
322
322
  } else if (requestBody && common.contentEncoding(req.headers, 'deflate')) {
323
323
  if (typeof zlib.deflateSync !== 'function') {
324
324
  emitError(new Error('Deflate encoding is currently not supported in this version of Node.'));
325
325
  return;
326
326
  }
327
- requestBody = String(zlib.inflateSync(new Buffer(requestBody, 'hex')), 'hex')
327
+ requestBody = String(zlib.inflateSync(Buffer.from(requestBody, 'hex')), 'hex')
328
328
  }
329
329
 
330
330
  requestBody = JSON.parse(requestBody);
@@ -356,7 +356,7 @@ function RequestOverrider(req, options, interceptors, remove, cb) {
356
356
  }
357
357
 
358
358
  responseBuffers = _.map(buffers, function(buffer) {
359
- return new Buffer(buffer, 'hex');
359
+ return Buffer.from(buffer, 'hex');
360
360
  });
361
361
 
362
362
  } else {
@@ -368,7 +368,7 @@ function RequestOverrider(req, options, interceptors, remove, cb) {
368
368
  if(isBinaryRequestBodyBuffer && typeof(responseBody) === 'string') {
369
369
  // Try to create the buffer from the interceptor's body response as hex.
370
370
  try {
371
- responseBody = new Buffer(responseBody, 'hex');
371
+ responseBody = Buffer.from(responseBody, 'hex');
372
372
  } catch(err) {
373
373
  debug('exception during Buffer construction from hex data:', responseBody, '-', err);
374
374
  }
@@ -376,7 +376,7 @@ function RequestOverrider(req, options, interceptors, remove, cb) {
376
376
  // Creating buffers does not necessarily throw errors, check for difference in size
377
377
  if (!responseBody || (interceptor.body.length > 0 && responseBody.length === 0)) {
378
378
  // We fallback on constructing buffer from utf8 representation of the body.
379
- responseBody = new Buffer(interceptor.body, 'utf8');
379
+ responseBody = Buffer.from(interceptor.body, 'utf8');
380
380
  }
381
381
  }
382
382
  }
@@ -402,23 +402,27 @@ function RequestOverrider(req, options, interceptors, remove, cb) {
402
402
  if (responseBody) {
403
403
  debug('transform the response body');
404
404
 
405
- if (Array.isArray(responseBody) &&
406
- responseBody.length >= 2 &&
407
- responseBody.length <= 3 &&
408
- typeof responseBody[0] == 'number')
409
- {
405
+ if (Array.isArray(responseBody)) {
410
406
  debug('response body is array: %j', responseBody);
411
- response.statusCode = Number(responseBody[0]);
412
- debug('new headers: %j', responseBody[2]);
413
- if (! response.headers) response.headers = {};
414
- _.assign(response.headers, responseBody[2] || {});
415
- debug('response.headers after: %j', response.headers);
416
- responseBody = responseBody[1];
417
-
418
- response.rawHeaders = response.rawHeaders || [];
419
- Object.keys(response.headers).forEach(function(key) {
420
- response.rawHeaders.push(key, response.headers[key]);
421
- });
407
+
408
+ if (!isNaN(Number(responseBody[0])))
409
+ {
410
+ response.statusCode = Number(responseBody[0]);
411
+ }
412
+
413
+ if (responseBody.length >= 2 && responseBody.length <= 3)
414
+ {
415
+ debug('new headers: %j', responseBody[2]);
416
+ if (!response.headers) response.headers = {};
417
+ _.assign(response.headers, responseBody[2] || {});
418
+ debug('response.headers after: %j', response.headers);
419
+ responseBody = responseBody[1];
420
+
421
+ response.rawHeaders = response.rawHeaders || [];
422
+ Object.keys(response.headers).forEach(function(key) {
423
+ response.rawHeaders.push(key, response.headers[key]);
424
+ });
425
+ }
422
426
  }
423
427
 
424
428
  if (interceptor.delayInMs) {
@@ -442,7 +446,7 @@ function RequestOverrider(req, options, interceptors, remove, cb) {
442
446
  });
443
447
  } else if (responseBody && !Buffer.isBuffer(responseBody)) {
444
448
  if (typeof responseBody === 'string') {
445
- responseBody = new Buffer(responseBody);
449
+ responseBody = Buffer.from(responseBody);
446
450
  } else {
447
451
  responseBody = JSON.stringify(responseBody);
448
452
  response.headers['content-type'] = 'application/json';
package/lib/scope.js CHANGED
@@ -332,9 +332,12 @@ function define(nockDefs) {
332
332
  nock.matchHeader(k, reqheaders[k]);
333
333
  }
334
334
  }
335
- if (nockDef.filteringRequestBody) {
336
- nock.filteringRequestBody(nockDef.filteringRequestBody);
337
- }
335
+ var acceptableFilters = ['filteringRequestBody', 'filteringPath'];
336
+ acceptableFilters.forEach((filter) => {
337
+ if (nockDef[filter]) {
338
+ nock[filter](nockDef[filter]);
339
+ }
340
+ });
338
341
  nock.intercept(npath, method, body).reply(status, response, rawHeaders);
339
342
  }
340
343
 
package/lib/socket.js CHANGED
@@ -58,7 +58,7 @@ Socket.prototype.applyDelay = function applyDelay(delayMs) {
58
58
  };
59
59
 
60
60
  Socket.prototype.getPeerCertificate = function getPeerCertificate() {
61
- return new Buffer((Math.random() * 10000 + Date.now()).toString()).toString('base64');
61
+ return Buffer.from((Math.random() * 10000 + Date.now()).toString()).toString('base64');
62
62
  };
63
63
 
64
64
  Socket.prototype.destroy = function destroy() {
package/package.json CHANGED
@@ -7,154 +7,8 @@
7
7
  "testing",
8
8
  "isolation"
9
9
  ],
10
- "version": "9.6.1",
10
+ "version": "10.0.3",
11
11
  "author": "Pedro Teixeira <pedro.teixeira@gmail.com>",
12
- "contributors": [
13
- {
14
- "name": "Bin Chang",
15
- "url": "https://github.com/BinChang"
16
- },
17
- {
18
- "name": "Roman Hotsiy",
19
- "url": "https://github.com/RomanGotsiy"
20
- },
21
- {
22
- "name": "Jeffrey Jagoda",
23
- "url": "https://github.com/jagoda"
24
- },
25
- {
26
- "name": "Hidenari Nozaki",
27
- "url": "https://github.com/ghiden"
28
- },
29
- {
30
- "name": "Ken Sheedlo",
31
- "url": "https://github.com/ksheedlo"
32
- },
33
- {
34
- "name": "Douglas Eggleton",
35
- "url": "https://github.com/douglaseggleton"
36
- },
37
- {
38
- "name": "José F. Romaniello",
39
- "url": "https://github.com/jfromaniello"
40
- },
41
- {
42
- "name": "Benjamin Urban",
43
- "url": "https://github.com/benurb"
44
- },
45
- {
46
- "name": "Justin",
47
- "url": "https://github.com/justincy"
48
- },
49
- {
50
- "name": "Brett Porter"
51
- },
52
- {
53
- "name": "Matt Olson"
54
- },
55
- {
56
- "name": "Rémy HUBSCHER"
57
- },
58
- {
59
- "name": "Roly Fentanes"
60
- },
61
- {
62
- "name": "Alexander Simmerl"
63
- },
64
- {
65
- "name": "Pedro Teixeira"
66
- },
67
- {
68
- "name": "Nuno Job"
69
- },
70
- {
71
- "name": "Ian Young"
72
- },
73
- {
74
- "name": "nilsbunger"
75
- },
76
- {
77
- "name": "bacchusrx",
78
- "email": "bacchusrx@eightstar.ca"
79
- },
80
- {
81
- "name": "Fabiano França"
82
- },
83
- {
84
- "name": "Sascha Drews"
85
- },
86
- {
87
- "name": "Mike Swift"
88
- },
89
- {
90
- "name": "James Herdman"
91
- },
92
- {
93
- "name": "David Björklund"
94
- },
95
- {
96
- "name": "Andrew Kramolisch"
97
- },
98
- {
99
- "name": "Balazs Nagy"
100
- },
101
- {
102
- "name": "Brian J Brennan"
103
- },
104
- {
105
- "name": "Attila Incze"
106
- },
107
- {
108
- "name": "Mac Angell"
109
- },
110
- {
111
- "name": "Tom Hosford"
112
- },
113
- {
114
- "name": "Aurélien Thieriot"
115
- },
116
- {
117
- "name": "Alex Zylman"
118
- },
119
- {
120
- "name": "Celestino Gomes",
121
- "email": "contact@tinogomes.com"
122
- },
123
- {
124
- "name": "David Rousselie"
125
- },
126
- {
127
- "name": "spenceralger"
128
- },
129
- {
130
- "name": "Ivan Erceg",
131
- "url": "https://github.com/ierceg",
132
- "email": "ivan@softwaremarbles.com"
133
- },
134
- {
135
- "name": "Keith Laban",
136
- "url": "https://github.com/kelaban",
137
- "email": "kelaban17@gmail.com"
138
- },
139
- {
140
- "name": "Rui Marinho",
141
- "url": "https://github.com/ruimarinho",
142
- "email": "ruipmarinho@gmail.com"
143
- },
144
- {
145
- "name": "David Pate",
146
- "url": "https://github.com/DavidTPate",
147
- "email": "davidtpate@gmail.com"
148
- },
149
- {
150
- "name": "Matt Oakes",
151
- "url": "https://github.com/matto1990"
152
- },
153
- {
154
- "name": "Ian Walker-Sperber",
155
- "url": "https://github.com/ianwsperber"
156
- }
157
- ],
158
12
  "repository": {
159
13
  "type": "git",
160
14
  "url": "https://github.com/nock/nock.git"
@@ -168,7 +22,7 @@
168
22
  "main": "./index",
169
23
  "dependencies": {
170
24
  "chai": "^4.1.2",
171
- "debug": "^3.1.0",
25
+ "debug": "^4.1.0",
172
26
  "deep-equal": "^1.0.0",
173
27
  "json-stringify-safe": "^5.0.1",
174
28
  "lodash": "^4.17.5",
@@ -192,16 +46,16 @@
192
46
  "restify-clients": "^2.2.0",
193
47
  "rimraf": "^2.6.2",
194
48
  "semantic-release": "^15.0.0",
195
- "superagent": "^3.8.2",
49
+ "superagent": "^4.0.0",
196
50
  "tap": "^12.0.0"
197
51
  },
198
52
  "scripts": {
199
- "unit": "tap --harmony ./tests/test_*.js",
53
+ "unit": "tap --coverage ./tests/test_*.js",
200
54
  "pretest": "npm run -s lint",
201
55
  "test": "npm run -s unit",
202
- "coverage": "nyc tap --harmony ./tests/test_*.js",
203
- "coveralls": "cat ./coverage/lcov.info | coveralls",
204
- "lint": "eslint '**/*.js'",
56
+ "coverage": "tap --coverage-report=html && open coverage/lcov-report/index.html",
57
+ "coverage:upload": "tap --coverage-report=text-lcov | coveralls",
58
+ "lint": "eslint \"**/*.js\"",
205
59
  "toc": "markdown-toc -i README.md && markdown-toc -i CONTRIBUTING.md ",
206
60
  "semantic-release": "semantic-release"
207
61
  },