0
# Request Interception
1
2
This document covers the core functionality for creating scopes and intercepting HTTP requests with nock.
3
4
## Creating Scopes
5
6
The main nock function creates a scope that defines the base URL and configuration for intercepting requests.
7
8
```javascript { .api }
9
function nock(basePath: string | RegExp | Url | URL, options?: Options): Scope;
10
```
11
12
### Parameters
13
14
- `basePath`: The base URL, hostname, or pattern to intercept. Can be:
15
- String URL: `"https://api.example.com"`
16
- RegExp pattern: `/api\.example\.com/`
17
- URL object: `new URL("https://api.example.com")`
18
- `options`: Optional configuration for the scope
19
20
### Examples
21
22
```javascript
23
// Basic hostname interception
24
const scope = nock("https://api.example.com");
25
26
// Intercept all subdomains
27
const scope = nock(/.*\.example\.com/);
28
29
// With options
30
const scope = nock("https://api.example.com", {
31
allowUnmocked: true,
32
encodedQueryParams: true
33
});
34
```
35
36
## HTTP Method Interceptors
37
38
The Scope provides methods for intercepting different HTTP verbs.
39
40
```javascript { .api }
41
interface Scope extends NodeJS.EventEmitter {
42
get(uri: string | RegExp | ((uri: string) => boolean), requestBody?: RequestBodyMatcher, options?: Options): Interceptor;
43
post(uri: string | RegExp | ((uri: string) => boolean), requestBody?: RequestBodyMatcher, options?: Options): Interceptor;
44
put(uri: string | RegExp | ((uri: string) => boolean), requestBody?: RequestBodyMatcher, options?: Options): Interceptor;
45
head(uri: string | RegExp | ((uri: string) => boolean), requestBody?: RequestBodyMatcher, options?: Options): Interceptor;
46
patch(uri: string | RegExp | ((uri: string) => boolean), requestBody?: RequestBodyMatcher, options?: Options): Interceptor;
47
merge(uri: string | RegExp | ((uri: string) => boolean), requestBody?: RequestBodyMatcher, options?: Options): Interceptor;
48
delete(uri: string | RegExp | ((uri: string) => boolean), requestBody?: RequestBodyMatcher, options?: Options): Interceptor;
49
options(uri: string | RegExp | ((uri: string) => boolean), requestBody?: RequestBodyMatcher, options?: Options): Interceptor;
50
}
51
```
52
53
### Parameters
54
55
- `uri`: The path portion of the URL to match. Can be:
56
- String path: `"/users/123"`
57
- RegExp pattern: `/\/users\/\d+/`
58
- Function predicate: `(uri) => uri.includes("users")`
59
- `requestBody`: Optional body matcher for POST/PUT/PATCH requests
60
- `options`: Optional interceptor-specific options
61
62
### Examples
63
64
```javascript
65
// GET request
66
nock("https://api.example.com")
67
.get("/users")
68
.reply(200, [{ id: 1, name: "Alice" }]);
69
70
// POST request with body matching
71
nock("https://api.example.com")
72
.post("/users", { name: "Bob", email: "bob@example.com" })
73
.reply(201, { id: 2, name: "Bob", email: "bob@example.com" });
74
75
// Dynamic path matching
76
nock("https://api.example.com")
77
.get(/\/users\/\d+/)
78
.reply(200, (uri) => {
79
const id = uri.split("/").pop();
80
return { id: parseInt(id), name: `User ${id}` };
81
});
82
83
// Function-based URI matching
84
nock("https://api.example.com")
85
.get((uri) => uri.includes("search"))
86
.reply(200, { results: [] });
87
```
88
89
## Generic Interceptor
90
91
For custom HTTP methods or more control over interception:
92
93
```javascript { .api }
94
intercept(
95
uri: string | RegExp | ((uri: string) => boolean),
96
method: string,
97
requestBody?: RequestBodyMatcher,
98
options?: Options
99
): Interceptor;
100
```
101
102
### Examples
103
104
```javascript
105
// Custom HTTP method
106
nock("https://api.example.com")
107
.intercept("/data", "PURGE")
108
.reply(204);
109
110
// Case-insensitive method
111
nock("https://api.example.com")
112
.intercept("/users", "get") // lowercase also works
113
.reply(200, []);
114
```
115
116
## Scope Configuration
117
118
Scopes can be configured with default behaviors that apply to all interceptors in that scope.
119
120
### Default Reply Headers
121
122
```javascript { .api }
123
defaultReplyHeaders(headers: ReplyHeaders): this;
124
```
125
126
Set headers that will be included in all responses from this scope.
127
128
```javascript
129
const scope = nock("https://api.example.com")
130
.defaultReplyHeaders({
131
"Content-Type": "application/json",
132
"X-API-Version": "1.0"
133
});
134
135
scope.get("/users").reply(200, []); // Will include the default headers
136
```
137
138
### Persistence
139
140
```javascript { .api }
141
persist(flag?: boolean): this;
142
```
143
144
Makes the scope persistent, meaning interceptors can be matched multiple times.
145
146
```javascript
147
// Persist all interceptors in this scope
148
const scope = nock("https://api.example.com")
149
.persist()
150
.get("/users")
151
.reply(200, []);
152
153
// This interceptor can now be called multiple times
154
```
155
156
### Content Length and Date Headers
157
158
```javascript { .api }
159
replyContentLength(): this;
160
replyDate(d?: Date): this;
161
```
162
163
Automatically add Content-Length and Date headers to responses.
164
165
```javascript
166
const scope = nock("https://api.example.com")
167
.replyContentLength()
168
.replyDate(new Date("2023-01-01"))
169
.get("/users")
170
.reply(200, []);
171
```
172
173
## Scope State Management
174
175
### Completion Checking
176
177
```javascript { .api }
178
interface Scope {
179
done(): void;
180
isDone(): boolean;
181
pendingMocks(): string[];
182
activeMocks(): string[];
183
}
184
```
185
186
- `done()`: Asserts that all interceptors in this scope have been satisfied. Throws if any are pending.
187
- `isDone()`: Returns true if all interceptors in this scope have been satisfied
188
- `pendingMocks()`: Returns array of string descriptions of pending interceptors in this scope
189
- `activeMocks()`: Returns array of string descriptions of active interceptors in this scope
190
191
### Examples
192
193
```javascript
194
const scope = nock("https://api.example.com")
195
.get("/users")
196
.reply(200, [])
197
.post("/users")
198
.reply(201, { id: 1 });
199
200
console.log(scope.isDone()); // false
201
console.log(scope.pendingMocks()); // ["GET https://api.example.com:443/users", "POST https://api.example.com:443/users"]
202
203
// After making the GET request
204
console.log(scope.pendingMocks()); // ["POST https://api.example.com:443/users"]
205
206
// After making both requests
207
scope.done(); // Passes without throwing
208
```
209
210
## Options Interface
211
212
```javascript { .api }
213
interface Options {
214
allowUnmocked?: boolean;
215
reqheaders?: Record<string, RequestHeaderMatcher>;
216
badheaders?: string[];
217
filteringScope?: (scope: string) => boolean;
218
encodedQueryParams?: boolean;
219
}
220
```
221
222
### Option Details
223
224
- `allowUnmocked`: Allow requests to this scope that don't match any interceptor to pass through to the real server
225
- `reqheaders`: Require specific headers to be present in requests
226
- `badheaders`: Headers that must NOT be present in requests
227
- `filteringScope`: Function to filter/transform the scope string for matching
228
- `encodedQueryParams`: Whether query parameters should be matched in encoded form
229
230
### Examples
231
232
```javascript
233
// Allow unmatched requests to pass through
234
const scope = nock("https://api.example.com", { allowUnmocked: true })
235
.get("/users")
236
.reply(200, []);
237
238
// Require authentication header
239
const scope = nock("https://api.example.com", {
240
reqheaders: {
241
authorization: "Bearer token123"
242
}
243
});
244
245
// Reject requests with certain headers
246
const scope = nock("https://api.example.com", {
247
badheaders: ["x-debug-mode"]
248
});
249
```