HTTP server mocking and expectations library for Node.js testing environments
npx @tessl/cli install tessl/npm-nock@14.0.00
# Nock
1
2
Nock is an HTTP server mocking and expectations library for Node.js that enables developers to test modules that perform HTTP requests in complete isolation. It intercepts HTTP/HTTPS requests to external services and allows you to define mock responses, making tests fast, deterministic, and independent of external network resources.
3
4
## Package Information
5
6
- **Package Name**: nock
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install nock`
10
11
## Core Imports
12
13
CommonJS:
14
15
```javascript
16
const nock = require("nock");
17
```
18
19
ES modules (default import):
20
21
```javascript
22
import nock from "nock";
23
```
24
25
ES modules (named imports - for TypeScript projects):
26
27
```typescript
28
import nock, {
29
cleanAll,
30
activate,
31
isActive,
32
isDone,
33
pendingMocks,
34
activeMocks,
35
disableNetConnect,
36
enableNetConnect
37
} from "nock";
38
```
39
40
## Basic Usage
41
42
```javascript
43
const nock = require("nock");
44
45
// Mock an HTTP GET request
46
const scope = nock("https://api.example.com")
47
.get("/users/123")
48
.reply(200, { id: 123, name: "John Doe" });
49
50
// Your code that makes the HTTP request will now receive the mock response
51
// After the request is made, verify it was called:
52
scope.done(); // Throws if the request wasn't made
53
```
54
55
## Architecture
56
57
Nock is built around several key components:
58
59
- **Scopes**: Define the base URL and common configuration for a group of interceptors
60
- **Interceptors**: Specify request matching criteria and define mock responses
61
- **Global Control**: Functions to manage nock's activation state and cleanup
62
- **Recording System**: Capture real HTTP traffic for later playback as fixtures
63
- **Back Mode**: Fixture-based testing workflow for integration with existing test suites
64
65
## Capabilities
66
67
### HTTP Request Interception
68
69
Core functionality for creating scopes and intercepting HTTP requests with flexible matching criteria.
70
71
```javascript { .api }
72
function nock(basePath: string | RegExp | Url | URL, options?: Options): Scope;
73
```
74
75
[Request Interception](./request-interception.md)
76
77
### Response Definition
78
79
Define mock responses with various data types, headers, and timing controls.
80
81
```javascript { .api }
82
interface Interceptor {
83
reply(statusCode?: number, body?: ReplyBody, headers?: ReplyHeaders): Scope;
84
replyWithError(errorMessage: string | object): Scope;
85
replyWithFile(statusCode: number, fileName: string, headers?: ReplyHeaders): Scope;
86
delay(ms: number | DelayOptions): this;
87
}
88
```
89
90
[Response Definition](./response-definition.md)
91
92
### Request Matching
93
94
Advanced request matching including headers, query parameters, and request bodies.
95
96
```javascript { .api }
97
interface Scope {
98
matchHeader(name: string, value: RequestHeaderMatcher): this;
99
filteringPath(regex: RegExp, replace: string): this;
100
filteringPath(fn: (path: string) => string): this;
101
filteringRequestBody(regex: RegExp, replace: string): this;
102
filteringRequestBody(
103
fn: (body: string, recordedBody: string) => string
104
): this;
105
}
106
107
interface Interceptor {
108
query(matcher: QueryMatcher): this;
109
matchHeader(name: string, value: RequestHeaderMatcher): this;
110
basicAuth(options: { user: string; pass?: string }): this;
111
}
112
```
113
114
[Request Matching](./request-matching.md)
115
116
### Global Management
117
118
Control nock's global state, cleanup interceptors, manage network access, and load fixtures.
119
120
```javascript { .api }
121
function cleanAll(): void;
122
function activate(): void;
123
function isActive(): boolean;
124
function isDone(): boolean;
125
function pendingMocks(): string[];
126
function activeMocks(): string[];
127
function disableNetConnect(): void;
128
function enableNetConnect(matcher?: string | RegExp | ((host: string) => boolean)): void;
129
function removeInterceptor(interceptor: Interceptor | ReqOptions): boolean;
130
function abortPendingRequests(): void;
131
function load(path: string): Scope[];
132
function loadDefs(path: string): Definition[];
133
function define(definitions: Definition[]): Scope[];
134
```
135
136
[Global Management](./global-management.md)
137
138
### Recording and Playback
139
140
Record real HTTP traffic and replay it as fixtures for testing.
141
142
```javascript { .api }
143
interface Recorder {
144
rec(options?: boolean | RecorderOptions): void;
145
clear(): void;
146
play(): string[] | Definition[];
147
}
148
149
const recorder: Recorder;
150
function restore(): void;
151
```
152
153
[Recording and Playback](./recording-playback.md)
154
155
### Fixture-Based Testing (Back Mode)
156
157
Advanced fixture-based testing workflow with multiple modes for different testing scenarios.
158
159
```javascript { .api }
160
interface Back {
161
(fixtureName: string, nockedFn: (nockDone: () => void) => void): void;
162
(
163
fixtureName: string,
164
options: BackOptions,
165
nockedFn: (nockDone: () => void) => void
166
): void;
167
(fixtureName: string, options?: BackOptions): Promise<{
168
nockDone: () => void;
169
context: BackContext;
170
}>;
171
172
currentMode: BackMode;
173
fixtures: string;
174
setMode(mode: BackMode): void;
175
}
176
177
type BackMode = 'wild' | 'dryrun' | 'record' | 'update' | 'lockdown';
178
```
179
180
[Fixture-Based Testing](./fixture-testing.md)
181
182
## Types
183
184
### Core Types
185
186
```javascript { .api }
187
interface Options {
188
allowUnmocked?: boolean;
189
reqheaders?: Record<string, RequestHeaderMatcher>;
190
badheaders?: string[];
191
filteringScope?: (scope: string) => boolean;
192
encodedQueryParams?: boolean;
193
}
194
195
type RequestHeaderMatcher = string | RegExp | ((fieldValue: string) => boolean);
196
type RequestBodyMatcher =
197
| string
198
| Buffer
199
| RegExp
200
| DataMatcherArray
201
| DataMatcherMap
202
| ((body: any) => boolean);
203
204
type ReplyBody = string | Record<string, any> | Buffer | ReadStream;
205
type ReplyHeaders =
206
| Record<string, ReplyHeaderValue>
207
| Map<string, ReplyHeaderValue>
208
| ReplyHeaderValue[];
209
210
type ReplyHeaderValue = string | string[] | ReplyHeaderFunction;
211
type ReplyHeaderFunction = (
212
req: ClientRequest,
213
res: IncomingMessage,
214
body: string | Buffer
215
) => string | string[];
216
```
217
218
### Data Matching Types
219
220
```javascript { .api }
221
type DataMatcher =
222
| boolean
223
| number
224
| string
225
| null
226
| undefined
227
| RegExp
228
| DataMatcherArray
229
| DataMatcherMap;
230
231
interface DataMatcherArray extends ReadonlyArray<DataMatcher> {}
232
interface DataMatcherMap {
233
[key: string]: DataMatcher;
234
}
235
236
type QueryMatcher =
237
| boolean
238
| string
239
| DataMatcherMap
240
| URLSearchParams
241
| ((parsedObj: ParsedUrlQuery) => boolean);
242
```
243
244
### Definition Types
245
246
```javascript { .api }
247
interface Definition {
248
scope: string | RegExp;
249
path: string | RegExp;
250
port?: number | string;
251
method?: string;
252
status?: number;
253
body?: RequestBodyMatcher;
254
reqheaders?: Record<string, RequestHeaderMatcher>;
255
response?: ReplyBody;
256
headers?: ReplyHeaders;
257
options?: Options;
258
}
259
260
interface ReqOptions {
261
hostname?: string;
262
port?: number;
263
method?: string;
264
path?: string;
265
proto?: string;
266
headers?: Record<string, string>;
267
}
268
```
269
270
## Events
271
272
Nock provides a global event emitter for monitoring request interception:
273
274
```javascript { .api }
275
const emitter: NodeJS.EventEmitter;
276
```
277
278
Common events:
279
- `'no match'` - Emitted when a request doesn't match any interceptor
280
281
## Error Handling
282
283
Nock throws specific errors in various scenarios:
284
285
### Network Errors
286
287
- **NetConnectNotAllowedError**: Thrown when `disableNetConnect()` is active and a request doesn't match any interceptor
288
- Error code: `ENETUNREACH`
289
- Message: "Nock: Disallowed net connect for..."
290
291
### URL and Protocol Errors
292
293
- **TypeError**: Thrown for invalid URLs or unsupported protocols
294
- Invalid URL format: `new URL()` constructor errors
295
- Unsupported protocol: Only HTTP/HTTPS are supported
296
- Message example: "Protocol 'ftp:' not recognized..."
297
298
### Interceptor Configuration Errors
299
300
- **Error**: Thrown for invalid interceptor configurations
301
- Missing method parameter: "The 'method' parameter is required for an intercept call"
302
- Invalid path format: "Non-wildcard URL path strings must begin with a slash"
303
- Duplicate query definitions: "Query parameters have already been defined"
304
- Invalid status code: "Invalid undefined value for status code"
305
306
### Scope Verification Errors
307
308
- **AssertionError**: Thrown by `scope.done()` when interceptors haven't been satisfied
309
- Message lists pending interceptors that weren't matched
310
311
### File System Errors
312
313
- **Error**: Thrown by fixture loading functions when `fs` is unavailable
314
- Browser environments: "No fs" error from `loadDefs()`
315
- Invalid file path: Standard `fs.readFileSync()` errors
316
317
### JSON Parsing Errors
318
319
- **SyntaxError**: Thrown when fixture files contain invalid JSON
320
- **Error**: Thrown by `define()` for invalid definition format
321
- Missing required fields: "Method is required"
322
- Port conflicts: "Mismatched port numbers in scope and port properties"
323
324
### Common Error Handling Patterns
325
326
```javascript
327
try {
328
const scope = nock("https://api.example.com")
329
.get("/users")
330
.reply(200, []);
331
332
// Make request...
333
334
scope.done(); // May throw AssertionError
335
} catch (error) {
336
if (error.code === "ENETUNREACH") {
337
console.log("Network request blocked by nock");
338
} else if (error.name === "AssertionError") {
339
console.log("Unused interceptors:", nock.pendingMocks());
340
} else {
341
throw error; // Re-throw unexpected errors
342
}
343
}
344
```