0
# Request Mocking
1
2
Complete HTTP request object simulation with all standard properties and methods, designed for testing route handlers, middleware, and request processing logic.
3
4
## Capabilities
5
6
### Create Request
7
8
Creates a mock HTTP request object with configurable properties and methods.
9
10
```javascript { .api }
11
/**
12
* Creates a new mock HTTP request instance
13
* @param options - Configuration options for the mock request
14
* @returns Mock request object with all HTTP request properties and methods
15
*/
16
function createRequest<T extends RequestType = Request>(options?: RequestOptions): MockRequest<T>;
17
18
interface RequestOptions {
19
method?: RequestMethod;
20
url?: string;
21
originalUrl?: string;
22
baseUrl?: string;
23
path?: string;
24
params?: Params;
25
session?: Session;
26
cookies?: Cookies;
27
signedCookies?: Cookies;
28
headers?: Headers;
29
body?: Body;
30
query?: Query;
31
files?: Files;
32
ip?: string;
33
[key: string]: any;
34
}
35
36
type MockRequest<T extends RequestType> = T & {
37
// Mock configuration methods
38
_setParameter: (key: string, value?: string) => void;
39
_setSessionVariable: (variable: string, value?: string) => void;
40
_setCookiesVariable: (variable: string, value?: string) => void;
41
_setSignedCookiesVariable: (variable: string, value?: string) => void;
42
_setHeadersVariable: (variable: string, value: string) => void;
43
_setFilesVariable: (variable: string, value?: string) => void;
44
_setMethod: (method?: string) => void;
45
_setURL: (value?: string) => void;
46
_setOriginalUrl: (value?: string) => void;
47
_setBaseUrl: (value?: string) => void;
48
_setBody: (body?: Body) => void;
49
_addBody: (key: string, value?: any) => void;
50
51
// Enhanced headers with Web API methods
52
headers: HeaderWebAPI;
53
54
// Express-style computed properties
55
protocol: string;
56
secure: boolean;
57
ip: string;
58
ips: string[];
59
hostname: string;
60
host: string;
61
subdomains: string[];
62
path: string;
63
fresh: boolean;
64
stale: boolean;
65
xhr: boolean;
66
67
// Support custom properties
68
[key: string]: any;
69
};
70
71
interface HeaderWebAPI {
72
[header: string]: any;
73
74
// Web API Headers methods
75
append(name: string, value: string): void;
76
delete(name: string): void;
77
get(name: string): string | null;
78
has(name: string): boolean;
79
set(name: string, value: string): void;
80
forEach(callbackfn: (value: string, key: string, parent: HeaderWebAPI) => void, thisArg?: any): void;
81
82
// Iterator methods
83
entries(): IterableIterator<[string, string]>;
84
keys(): IterableIterator<string>;
85
values(): IterableIterator<string>;
86
[Symbol.iterator](): IterableIterator<[string, string]>;
87
}
88
```
89
90
**Usage Examples:**
91
92
```javascript
93
const httpMocks = require('node-mocks-http');
94
95
// Basic request
96
const request = httpMocks.createRequest({
97
method: 'GET',
98
url: '/users/123',
99
params: { id: '123' }
100
});
101
102
// Request with headers and body
103
const postRequest = httpMocks.createRequest({
104
method: 'POST',
105
url: '/api/users',
106
headers: {
107
'Content-Type': 'application/json',
108
'Authorization': 'Bearer token123'
109
},
110
body: {
111
name: 'John Doe',
112
email: 'john@example.com'
113
}
114
});
115
116
// Request with query parameters
117
const searchRequest = httpMocks.createRequest({
118
method: 'GET',
119
url: '/search?q=node&limit=10',
120
query: {
121
q: 'node',
122
limit: '10'
123
}
124
});
125
```
126
127
### Header Methods
128
129
Methods for accessing and manipulating HTTP headers.
130
131
```javascript { .api }
132
/**
133
* Get header value by name (case-insensitive)
134
* @param name - Header name
135
* @returns Header value or undefined
136
*/
137
getHeader(name: string): string | undefined;
138
139
/**
140
* Alias for getHeader
141
*/
142
header(name: string): string | undefined;
143
144
/**
145
* Alias for getHeader
146
*/
147
get(name: string): string | undefined;
148
```
149
150
**Usage Examples:**
151
152
```javascript
153
const request = httpMocks.createRequest({
154
headers: {
155
'Content-Type': 'application/json',
156
'User-Agent': 'test-agent'
157
}
158
});
159
160
console.log(request.get('Content-Type')); // 'application/json'
161
console.log(request.header('user-agent')); // 'test-agent' (case-insensitive)
162
console.log(request.getHeader('Authorization')); // undefined
163
```
164
165
### Content Type Methods
166
167
Methods for checking and validating content types.
168
169
```javascript { .api }
170
/**
171
* Check if request matches given content type(s)
172
* @param types - Content type or array of types to check
173
* @returns Matching type string or false
174
*/
175
is(...types: string[]): string | false | null;
176
```
177
178
**Usage Examples:**
179
180
```javascript
181
const request = httpMocks.createRequest({
182
headers: { 'Content-Type': 'application/json' },
183
body: { name: 'test' }
184
});
185
186
console.log(request.is('json')); // 'json'
187
console.log(request.is('html')); // false
188
console.log(request.is(['xml', 'json'])); // 'json'
189
```
190
191
### Content Negotiation
192
193
Methods for handling Accept headers and content negotiation.
194
195
```javascript { .api }
196
/**
197
* Check what content types the client accepts
198
* @param types - Content types to check
199
* @returns Best matching type or false
200
*/
201
accepts(types: string | string[]): string | false;
202
203
/**
204
* Check what encodings the client accepts
205
* @param encodings - Encodings to check
206
* @returns Best matching encoding or false
207
*/
208
acceptsEncodings(...encodings: string[]): string | false;
209
210
/**
211
* Check what charsets the client accepts
212
* @param charsets - Charsets to check
213
* @returns Best matching charset or false
214
*/
215
acceptsCharsets(...charsets: string[]): string | false;
216
217
/**
218
* Check what languages the client accepts
219
* @param languages - Languages to check
220
* @returns Best matching language or false
221
*/
222
acceptsLanguages(...languages: string[]): string | false;
223
```
224
225
### Range Requests
226
227
Support for HTTP Range requests.
228
229
```javascript { .api }
230
/**
231
* Parse Range header field
232
* @param size - Resource size
233
* @param opts - Range parsing options
234
* @returns Range result or undefined
235
*/
236
range(size: number, opts?: object): false | number | array | undefined;
237
```
238
239
### Parameter Access
240
241
Methods for accessing request parameters from various sources.
242
243
```javascript { .api }
244
/**
245
* Get parameter value from params, body, or query (in that order)
246
* @param name - Parameter name
247
* @param defaultValue - Default value if parameter not found
248
* @returns Parameter value or default
249
*/
250
param(name: string, defaultValue?: any): any;
251
```
252
253
**Usage Examples:**
254
255
```javascript
256
const request = httpMocks.createRequest({
257
params: { id: '123' },
258
body: { name: 'John' },
259
query: { sort: 'asc' }
260
});
261
262
console.log(request.param('id')); // '123' (from params)
263
console.log(request.param('name')); // 'John' (from body)
264
console.log(request.param('sort')); // 'asc' (from query)
265
console.log(request.param('missing', 'default')); // 'default'
266
```
267
268
### Stream Methods
269
270
Methods for handling request as a stream.
271
272
```javascript { .api }
273
/**
274
* Send data to the request stream
275
* @param data - Data to send (string, object, number, or Buffer)
276
*/
277
send(data: string | object | number | Buffer): void;
278
279
/**
280
* Destroy the request stream
281
*/
282
destroy(): void;
283
284
/**
285
* Async iterator for processing request data
286
*/
287
[Symbol.asyncIterator](): AsyncIterableIterator<Buffer>;
288
```
289
290
### Mock Configuration Methods
291
292
Methods for dynamically modifying the mock request (prefixed with `_`).
293
294
```javascript { .api }
295
/**
296
* Set a route parameter
297
* @param key - Parameter key
298
* @param value - Parameter value
299
*/
300
_setParameter(key: string, value?: string): void;
301
302
/**
303
* Set a session variable
304
* @param variable - Variable name
305
* @param value - Variable value
306
*/
307
_setSessionVariable(variable: string, value?: string): void;
308
309
/**
310
* Set a cookie variable
311
* @param variable - Cookie name
312
* @param value - Cookie value
313
*/
314
_setCookiesVariable(variable: string, value?: string): void;
315
316
/**
317
* Set a signed cookie variable
318
* @param variable - Cookie name
319
* @param value - Cookie value
320
*/
321
_setSignedCookiesVariable(variable: string, value?: string): void;
322
323
/**
324
* Set a header value
325
* @param variable - Header name
326
* @param value - Header value
327
*/
328
_setHeadersVariable(variable: string, value: string): void;
329
330
/**
331
* Set a file variable
332
* @param variable - File field name
333
* @param value - File value
334
*/
335
_setFilesVariable(variable: string, value?: string): void;
336
337
/**
338
* Set the HTTP method
339
* @param method - HTTP method
340
*/
341
_setMethod(method?: string): void;
342
343
/**
344
* Set the request URL
345
* @param value - URL path
346
*/
347
_setURL(value?: string): void;
348
349
/**
350
* Set the original URL
351
* @param value - Original URL
352
*/
353
_setOriginalUrl(value?: string): void;
354
355
/**
356
* Set the base URL
357
* @param value - Base URL path
358
*/
359
_setBaseUrl(value?: string): void;
360
361
/**
362
* Set the request body
363
* @param body - Request body object
364
*/
365
_setBody(body?: Body): void;
366
367
/**
368
* Add a property to the request body
369
* @param key - Body property key
370
* @param value - Body property value
371
*/
372
_addBody(key: string, value?: any): void;
373
```
374
375
### Express-style Computed Properties
376
377
Request objects include Express-compatible computed properties that derive values from headers and configuration.
378
379
```javascript { .api }
380
/**
381
* Request protocol (http or https)
382
*/
383
protocol: string;
384
385
/**
386
* Whether the connection is secure (https)
387
*/
388
secure: boolean;
389
390
/**
391
* Client IP address
392
*/
393
ip: string;
394
395
/**
396
* Array of IP addresses (when behind proxies)
397
*/
398
ips: string[];
399
400
/**
401
* Request hostname (without port)
402
*/
403
hostname: string;
404
405
/**
406
* Request host (with port if specified)
407
*/
408
host: string;
409
410
/**
411
* Array of subdomain parts
412
*/
413
subdomains: string[];
414
415
/**
416
* Request pathname (derived from URL)
417
*/
418
path: string;
419
420
/**
421
* Whether request is fresh (conditional GET)
422
*/
423
fresh: boolean;
424
425
/**
426
* Whether request is stale (opposite of fresh)
427
*/
428
stale: boolean;
429
430
/**
431
* Whether request is XMLHttpRequest
432
*/
433
xhr: boolean;
434
```
435
436
**Usage Examples:**
437
438
```javascript
439
const request = httpMocks.createRequest({
440
headers: {
441
'Host': 'api.example.com:8080',
442
'X-Forwarded-Proto': 'https',
443
'X-Requested-With': 'XMLHttpRequest'
444
},
445
url: '/users/123'
446
});
447
448
console.log(request.protocol); // 'https'
449
console.log(request.secure); // true
450
console.log(request.hostname); // 'api.example.com'
451
console.log(request.host); // 'api.example.com:8080'
452
console.log(request.path); // '/users/123'
453
console.log(request.xhr); // true
454
```
455
456
## Request Properties
457
458
The mock request includes all standard HTTP request properties:
459
460
- **method** (string): HTTP method (GET, POST, etc.)
461
- **url** (string): Request URL
462
- **originalUrl** (string): Original URL before processing
463
- **baseUrl** (string): Base URL portion
464
- **path** (string): URL path portion
465
- **params** (object): Route parameters
466
- **session** (object): Session data
467
- **cookies** (object): Request cookies
468
- **signedCookies** (object): Signed cookies
469
- **headers** (HeaderWebAPI): HTTP headers with Web API methods
470
- **body** (object): Request body data
471
- **query** (object): Query string parameters
472
- **files** (object): Uploaded files
473
- **ip** (string): Client IP address
474
- **ips** (array): Array of IP addresses
475
- **hostname** (string): Request hostname
476
- **subdomains** (array): Request subdomains