0
# Global Management
1
2
This document covers nock's global state management functions for controlling activation, cleanup, network access, and monitoring interceptors across all scopes.
3
4
## Activation Control
5
6
Manage nock's global activation state to control when HTTP interception is active.
7
8
```javascript { .api }
9
function activate(): void;
10
function isActive(): boolean;
11
```
12
13
### Activation
14
15
```javascript
16
const nock = require("nock");
17
18
// Activate nock globally
19
nock.activate();
20
21
// Check if nock is active
22
console.log(nock.isActive()); // true
23
24
// Create interceptors - these will now work
25
const scope = nock("https://api.example.com")
26
.get("/users")
27
.reply(200, []);
28
```
29
30
**Note**: Nock is automatically activated when you import/require it, so manual activation is typically not needed unless you've previously disabled it.
31
32
## Global Cleanup
33
34
Remove all interceptors and clean up nock's state.
35
36
```javascript { .api }
37
function cleanAll(): void;
38
```
39
40
```javascript
41
// Create multiple scopes with interceptors
42
nock("https://api.example.com").get("/users").reply(200, []);
43
nock("https://api.example.com").post("/users").reply(201, {});
44
nock("https://other-api.com").get("/data").reply(200, {});
45
46
console.log(nock.activeMocks().length); // 3
47
48
// Clean up all interceptors
49
nock.cleanAll();
50
51
console.log(nock.activeMocks().length); // 0
52
```
53
54
This is commonly used in test cleanup:
55
56
```javascript
57
// Jest/Mocha example
58
afterEach(() => {
59
nock.cleanAll();
60
});
61
```
62
63
## Interceptor Monitoring
64
65
Get information about active and pending interceptors across all scopes.
66
67
```javascript { .api }
68
function pendingMocks(): string[];
69
function activeMocks(): string[];
70
function isDone(): boolean;
71
```
72
73
### Pending Mocks
74
75
Get descriptions of interceptors that have been defined but not yet matched:
76
77
```javascript
78
nock("https://api.example.com")
79
.get("/users")
80
.reply(200, [])
81
.post("/users")
82
.reply(201, {});
83
84
console.log(nock.pendingMocks());
85
// Output: [
86
// "GET https://api.example.com:443/users",
87
// "POST https://api.example.com:443/users"
88
// ]
89
90
// After making a GET request to /users
91
console.log(nock.pendingMocks());
92
// Output: ["POST https://api.example.com:443/users"]
93
```
94
95
### Active Mocks
96
97
Get descriptions of all currently active interceptors (both matched and unmatched):
98
99
```javascript
100
const scope1 = nock("https://api.example.com")
101
.get("/users")
102
.reply(200, []);
103
104
const scope2 = nock("https://other-api.com")
105
.get("/data")
106
.reply(200, {});
107
108
console.log(nock.activeMocks());
109
// Output: [
110
// "GET https://api.example.com:443/users",
111
// "GET https://other-api.com:443/data"
112
// ]
113
```
114
115
### Global Done Check
116
117
Check if all interceptors across all scopes have been satisfied:
118
119
```javascript
120
nock("https://api.example.com")
121
.get("/users")
122
.reply(200, [])
123
.post("/users")
124
.reply(201, {});
125
126
console.log(nock.isDone()); // false
127
128
// Make both requests...
129
// After both requests are made:
130
console.log(nock.isDone()); // true
131
```
132
133
## Network Connection Control
134
135
Control whether real HTTP requests are allowed when no interceptors match.
136
137
### Disable Net Connect
138
139
```javascript { .api }
140
function disableNetConnect(): void;
141
```
142
143
Prevent any real HTTP requests from being made:
144
145
```javascript
146
nock.disableNetConnect();
147
148
// This will throw NetConnectNotAllowedError if no interceptor matches
149
// http.get("https://real-api.com/data", callback);
150
```
151
152
This is the default behavior and is useful for ensuring tests don't make unexpected network calls.
153
154
### Enable Net Connect
155
156
```javascript { .api }
157
function enableNetConnect(
158
matcher?: string | RegExp | ((host: string) => boolean)
159
): void;
160
```
161
162
Allow real HTTP requests, optionally with restrictions:
163
164
```javascript
165
// Allow all real HTTP requests
166
nock.enableNetConnect();
167
168
// Allow requests to specific host
169
nock.enableNetConnect("localhost");
170
171
// Allow requests matching regex pattern
172
nock.enableNetConnect(/^localhost/);
173
174
// Allow requests based on function predicate
175
nock.enableNetConnect((host) => {
176
return host.includes("localhost") || host.includes("127.0.0.1");
177
});
178
```
179
180
### Common Patterns
181
182
```javascript
183
// Allow localhost for integration tests
184
nock.enableNetConnect("localhost");
185
186
// Allow test database connections
187
nock.enableNetConnect((host) => host.includes("testdb"));
188
189
// Re-disable after tests
190
afterEach(() => {
191
nock.disableNetConnect();
192
});
193
```
194
195
## Interceptor Management
196
197
Remove specific interceptors and abort pending requests.
198
199
### Remove Specific Interceptor
200
201
```javascript { .api }
202
function removeInterceptor(interceptor: Interceptor | ReqOptions): boolean;
203
```
204
205
Remove a specific interceptor from nock's registry:
206
207
```javascript
208
const scope = nock("https://api.example.com");
209
const interceptor = scope.get("/users").reply(200, []);
210
211
// Remove this specific interceptor
212
const removed = nock.removeInterceptor(interceptor);
213
console.log(removed); // true if successfully removed
214
215
// Can also remove by request options
216
nock.removeInterceptor({
217
hostname: "api.example.com",
218
port: 443,
219
method: "GET",
220
path: "/users"
221
});
222
```
223
224
### Abort Pending Requests
225
226
```javascript { .api }
227
function abortPendingRequests(): void;
228
```
229
230
Abort all pending HTTP requests that are waiting for responses:
231
232
```javascript
233
// If you have pending requests that are stuck or taking too long
234
nock.abortPendingRequests();
235
```
236
237
This is useful in test teardown to ensure no hanging requests:
238
239
```javascript
240
afterEach(() => {
241
nock.abortPendingRequests();
242
nock.cleanAll();
243
});
244
```
245
246
## Event System
247
248
Monitor nock's behavior using the global event emitter.
249
250
```javascript { .api }
251
const emitter: NodeJS.EventEmitter;
252
```
253
254
### No Match Event
255
256
Listen for requests that don't match any interceptor:
257
258
```javascript
259
nock.emitter.on("no match", (req) => {
260
console.log("Unmatched request:", req.method, req.path);
261
console.log("Headers:", req.headers);
262
});
263
264
// Enable net connect to allow unmatched requests
265
nock.enableNetConnect();
266
267
// This request won't match any interceptor and will trigger the event
268
// (then proceed to the real server because net connect is enabled)
269
```
270
271
### Custom Event Handling
272
273
```javascript
274
// Track when interceptors are used
275
nock.emitter.on("no match", (req) => {
276
// Log unmatched requests for debugging
277
console.warn(`Unmatched request: ${req.method} ${req.path}`);
278
279
// Optionally fail tests on unmatched requests
280
if (process.env.NODE_ENV === "test") {
281
throw new Error(`Unexpected HTTP request: ${req.method} ${req.path}`);
282
}
283
});
284
```
285
286
## Error Handling
287
288
Understand the errors that nock's global functions can throw.
289
290
### NetConnectNotAllowedError
291
292
Thrown when `disableNetConnect()` is active and a request doesn't match any interceptor:
293
294
```javascript
295
nock.disableNetConnect();
296
297
try {
298
// This will throw if no interceptor matches
299
await fetch("https://unmocked-api.com/data");
300
} catch (error) {
301
if (error.code === "ENETUNREACH") {
302
console.log("Real network request was blocked by nock");
303
}
304
}
305
```
306
307
## Complete Example: Test Suite Setup
308
309
Here's how to set up nock for a complete test suite:
310
311
```javascript
312
const nock = require("nock");
313
314
describe("API Integration Tests", () => {
315
beforeEach(() => {
316
// Ensure nock is active and net connect is disabled
317
nock.activate();
318
nock.disableNetConnect();
319
320
// Allow localhost for test database/server
321
nock.enableNetConnect("localhost");
322
});
323
324
afterEach(() => {
325
// Verify all interceptors were used
326
if (!nock.isDone()) {
327
console.warn("Unused interceptors:", nock.pendingMocks());
328
}
329
330
// Clean up all interceptors
331
nock.abortPendingRequests();
332
nock.cleanAll();
333
});
334
335
it("should handle user creation", async () => {
336
const scope = nock("https://api.example.com")
337
.post("/users", { name: "Alice" })
338
.reply(201, { id: 1, name: "Alice" });
339
340
// Your test code here...
341
342
// Verify the interceptor was used
343
expect(scope.isDone()).toBe(true);
344
});
345
346
it("should handle network errors gracefully", async () => {
347
nock("https://api.example.com")
348
.get("/users")
349
.replyWithError("Network timeout");
350
351
// Test your error handling...
352
});
353
});
354
```
355
356
## Fixture Loading Utilities
357
358
Load and define interceptors from JSON fixture files programmatically.
359
360
### Load Definitions
361
362
```javascript { .api }
363
function loadDefs(path: string): Definition[];
364
```
365
366
Load fixture definitions from a JSON file without creating interceptors:
367
368
```javascript
369
const nock = require("nock");
370
371
// Load definitions from file
372
const definitions = nock.loadDefs("./fixtures/api-responses.json");
373
console.log(`Loaded ${definitions.length} fixture definitions`);
374
375
// Process definitions before creating interceptors
376
const processedDefs = definitions.map(def => {
377
// Modify definitions as needed
378
if (def.scope.includes("api.example.com")) {
379
def.response = { modified: true, ...JSON.parse(def.response) };
380
}
381
return def;
382
});
383
384
// Create interceptors from processed definitions
385
const scopes = nock.define(processedDefs);
386
```
387
388
**Note**: This function requires the `fs` module and will throw an error in browser environments.
389
390
### Load and Define
391
392
```javascript { .api }
393
function load(path: string): Scope[];
394
```
395
396
Load fixture definitions from a JSON file and immediately create interceptors:
397
398
```javascript
399
// Load fixtures and create interceptors in one step
400
const scopes = nock.load("./fixtures/user-api.json");
401
console.log(`Created ${scopes.length} scopes from fixtures`);
402
403
// Equivalent to: nock.define(nock.loadDefs(path))
404
```
405
406
### Define Interceptors
407
408
```javascript { .api }
409
function define(definitions: Definition[]): Scope[];
410
```
411
412
Create interceptors from an array of definition objects:
413
414
```javascript
415
const definitions = [
416
{
417
scope: "https://api.example.com:443",
418
method: "GET",
419
path: "/users",
420
status: 200,
421
response: [{ id: 1, name: "Alice" }]
422
},
423
{
424
scope: "https://api.example.com:443",
425
method: "POST",
426
path: "/users",
427
body: { name: "Bob" },
428
status: 201,
429
response: { id: 2, name: "Bob" }
430
}
431
];
432
433
// Create interceptors from definitions
434
const scopes = nock.define(definitions);
435
console.log(`Created ${scopes.length} scopes`);
436
437
// Each scope can be used normally
438
scopes.forEach(scope => {
439
console.log("Active mocks:", scope.activeMocks());
440
});
441
```
442
443
### Fixture File Format
444
445
Fixture files should contain an array of Definition objects:
446
447
```json
448
[
449
{
450
"scope": "https://api.example.com:443",
451
"method": "GET",
452
"path": "/users",
453
"status": 200,
454
"response": "[{\"id\":1,\"name\":\"Alice\"}]",
455
"headers": {
456
"content-type": "application/json"
457
}
458
},
459
{
460
"scope": "https://api.example.com:443",
461
"method": "POST",
462
"path": "/users",
463
"body": "{\"name\":\"Bob\"}",
464
"status": 201,
465
"response": "{\"id\":2,\"name\":\"Bob\"}",
466
"reqheaders": {
467
"content-type": "application/json"
468
}
469
}
470
]
471
```
472
473
### Advanced Fixture Processing
474
475
```javascript
476
// Load and process fixtures with scope filtering
477
const rawDefs = nock.loadDefs("./fixtures/comprehensive-api.json");
478
479
// Filter definitions by scope
480
const apiDefs = rawDefs.filter(def =>
481
def.scope.includes("api.example.com")
482
);
483
484
// Add scope-level filtering before defining
485
const scope = nock("https://api.example.com", {
486
filteringScope: (scope) => scope.replace(/\d+/, "ID")
487
});
488
489
// Define interceptors with preprocessing
490
const scopes = nock.define(apiDefs.map(def => ({
491
...def,
492
// Add default options to all definitions
493
options: {
494
...def.options,
495
allowUnmocked: true
496
}
497
})));
498
```
499
500
## Debugging Utilities
501
502
Use global functions for debugging interceptor issues:
503
504
```javascript
505
// Log all active interceptors
506
console.log("Active mocks:", nock.activeMocks());
507
508
// Log pending interceptors
509
console.log("Pending mocks:", nock.pendingMocks());
510
511
// Check global state
512
console.log("Nock is active:", nock.isActive());
513
console.log("All interceptors done:", nock.isDone());
514
515
// Set up detailed logging
516
nock.emitter.on("no match", (req) => {
517
console.log("❌ No match for:", req.method, req.path);
518
console.log("Available interceptors:", nock.activeMocks());
519
});
520
```