0
# Response Mocking
1
2
Full HTTP response object simulation with status codes, headers, cookies, and all response methods. Includes comprehensive introspection methods for test verification.
3
4
## Capabilities
5
6
### Create Response
7
8
Creates a mock HTTP response object with configurable properties and methods.
9
10
```javascript { .api }
11
/**
12
* Creates a new mock HTTP response instance
13
* @param options - Configuration options for the mock response
14
* @returns Mock response object with all HTTP response properties and methods
15
*/
16
function createResponse<T extends ResponseType = Response>(options?: ResponseOptions): MockResponse<T>;
17
18
interface ResponseOptions {
19
eventEmitter?: any;
20
writableStream?: any;
21
req?: any;
22
locals?: any;
23
}
24
25
type MockResponse<T extends ResponseType> = T & {
26
// Introspection methods for testing
27
_isEndCalled: () => boolean;
28
_getHeaders: () => HeaderWebAPI;
29
_getData: () => any;
30
_getJSONData: () => any;
31
_getBuffer: () => Buffer;
32
_getChunks: () => any[];
33
_getLocals: () => any;
34
_getStatusCode: () => number;
35
_getStatusMessage: () => string;
36
_isJSON: () => boolean;
37
_isUTF8: () => boolean;
38
_isDataLengthValid: () => boolean;
39
_getRedirectUrl: () => string;
40
_getRenderData: () => any;
41
_getRenderView: () => string;
42
43
// Response cookies
44
cookies: { [name: string]: ResponseCookie };
45
};
46
47
interface ResponseCookie {
48
value: any;
49
options: CookieOptions;
50
}
51
```
52
53
**Usage Examples:**
54
55
```javascript
56
const httpMocks = require('node-mocks-http');
57
58
// Basic response
59
const response = httpMocks.createResponse();
60
61
// Response with custom locals
62
const responseWithLocals = httpMocks.createResponse({
63
locals: {
64
user: { id: 1, name: 'John' },
65
theme: 'dark'
66
}
67
});
68
69
// Response linked to a request (for format() method)
70
const { req, res } = httpMocks.createMocks();
71
```
72
73
### Status Methods
74
75
Methods for setting and managing response status codes.
76
77
```javascript { .api }
78
/**
79
* Set response status code (chainable)
80
* @param code - HTTP status code
81
* @returns Response instance for chaining
82
*/
83
status(code: number): MockResponse;
84
85
/**
86
* Send given HTTP status code with standard message
87
* @param statusCode - HTTP status code
88
* @returns Response instance
89
*/
90
sendStatus(statusCode: number): MockResponse;
91
```
92
93
**Usage Examples:**
94
95
```javascript
96
const response = httpMocks.createResponse();
97
98
// Set status code
99
response.status(404);
100
console.log(response.statusCode); // 404
101
102
// Send status with message
103
response.sendStatus(201); // Sets status to 201 and sends "Created"
104
```
105
106
### Header Methods
107
108
Comprehensive header management methods.
109
110
```javascript { .api }
111
/**
112
* Write response headers (should be called once)
113
* @param statusCode - HTTP status code
114
* @param statusMessage - Optional status message
115
* @param headers - Optional headers object
116
* @returns Response instance
117
*/
118
writeHead(statusCode: number, statusMessage?: string | object, headers?: object): MockResponse;
119
120
/**
121
* Set header field to value, or pass an object of header fields
122
* @param field - Header name or headers object
123
* @param val - Header value (if field is string)
124
* @returns Response instance
125
*/
126
set(field: string | object, val?: string | string[]): MockResponse;
127
128
/**
129
* Alias for set()
130
*/
131
header(field: string | object, val?: string | string[]): MockResponse;
132
133
/**
134
* Get header value by name
135
* @param name - Header name
136
* @returns Header value
137
*/
138
get(name: string): string | string[] | undefined;
139
140
/**
141
* Alias for get()
142
*/
143
getHeader(name: string): string | string[] | undefined;
144
145
/**
146
* Get all headers as object
147
* @returns Headers object
148
*/
149
getHeaders(): object;
150
151
/**
152
* Get array of header names
153
* @returns Array of header names
154
*/
155
getHeaderNames(): string[];
156
157
/**
158
* Check if header exists
159
* @param name - Header name
160
* @returns True if header exists
161
*/
162
hasHeader(name: string): boolean;
163
164
/**
165
* Set individual header
166
* @param name - Header name
167
* @param value - Header value
168
* @returns Response instance
169
*/
170
setHeader(name: string, value: string | string[]): MockResponse;
171
172
/**
173
* Append value to header
174
* @param name - Header name
175
* @param value - Value to append
176
* @returns Response instance
177
*/
178
appendHeader(name: string, value: string | string[]): MockResponse;
179
180
/**
181
* Append additional header field with value
182
* @param field - Header field name
183
* @param val - Header value
184
* @returns Response instance
185
*/
186
append(field: string, val: string | string[]): MockResponse;
187
188
/**
189
* Remove header by name
190
* @param name - Header name
191
*/
192
removeHeader(name: string): void;
193
```
194
195
### Core HTTP Methods
196
197
Methods for low-level HTTP response control.
198
199
```javascript { .api }
200
/**
201
* Write response headers (should be called once)
202
* @param statusCode - HTTP status code
203
* @param statusMessage - Optional status message
204
* @param headers - Optional headers object
205
* @returns Response instance
206
*/
207
writeHead(statusCode: number, statusMessage?: string | object, headers?: object): MockResponse;
208
```
209
210
### Content Methods
211
212
Methods for sending response content.
213
214
```javascript { .api }
215
/**
216
* Write data to response (can be called multiple times)
217
* @param data - Data to write
218
* @param encoding - Optional encoding
219
*/
220
write(data: string | Buffer | TypedArray, encoding?: string): void;
221
222
/**
223
* End the response with optional data
224
* @param data - Optional data to send
225
* @param encoding - Optional encoding
226
* @param callback - Optional callback
227
*/
228
end(data?: string | Buffer | TypedArray, encoding?: string, callback?: Function): void;
229
230
/**
231
* Send response data (Express-style)
232
* @param data - Data to send
233
* @returns Response instance
234
*/
235
send(data?: any): MockResponse;
236
237
/**
238
* Send JSON response
239
* @param data - Data to send as JSON
240
* @returns Response instance
241
*/
242
json(data?: any): MockResponse;
243
244
/**
245
* Send JSONP response
246
* @param data - Data to send as JSONP
247
* @returns Response instance
248
*/
249
jsonp(data?: any): MockResponse;
250
```
251
252
**Usage Examples:**
253
254
```javascript
255
const response = httpMocks.createResponse();
256
257
// Send simple response
258
response.send('Hello World');
259
260
// Send JSON response
261
response.json({ message: 'Success', data: [1, 2, 3] });
262
263
// Send status with data
264
response.status(201).json({ id: 123, created: true });
265
266
// Write data incrementally
267
response.write('Chunk 1');
268
response.write('Chunk 2');
269
response.end('Final chunk');
270
```
271
272
### Content Type Methods
273
274
Methods for setting content types and handling attachments.
275
276
```javascript { .api }
277
/**
278
* Set Content-Type header based on file extension or mime type
279
* @param type - File extension or mime type
280
* @returns Response instance
281
*/
282
type(type: string): MockResponse;
283
284
/**
285
* Alias for type()
286
*/
287
contentType(type: string): MockResponse;
288
289
/**
290
* Set Content-Disposition header to attachment
291
* @param filename - Optional filename
292
* @returns Response instance
293
*/
294
attachment(filename?: string): MockResponse;
295
```
296
297
**Usage Examples:**
298
299
```javascript
300
const response = httpMocks.createResponse();
301
302
// Set content type by extension
303
response.type('json'); // Sets 'application/json'
304
response.type('html'); // Sets 'text/html'
305
306
// Set content type by mime type
307
response.type('application/pdf');
308
309
// Set as attachment
310
response.attachment('report.pdf');
311
```
312
313
### Cookie Methods
314
315
Methods for managing response cookies.
316
317
```javascript { .api }
318
/**
319
* Set cookie
320
* @param name - Cookie name
321
* @param value - Cookie value
322
* @param options - Cookie options
323
* @returns Response instance
324
*/
325
cookie(name: string, value: any, options?: CookieOptions): MockResponse;
326
327
/**
328
* Clear cookie
329
* @param name - Cookie name
330
* @param options - Cookie options
331
* @returns Response instance
332
*/
333
clearCookie(name: string, options?: CookieOptions): MockResponse;
334
```
335
336
**Usage Examples:**
337
338
```javascript
339
const response = httpMocks.createResponse();
340
341
// Set simple cookie
342
response.cookie('sessionId', 'abc123');
343
344
// Set cookie with options
345
response.cookie('preferences', 'dark-theme', {
346
maxAge: 86400000, // 24 hours
347
httpOnly: true,
348
secure: true
349
});
350
351
// Clear cookie
352
response.clearCookie('sessionId');
353
```
354
355
### Redirect and Render
356
357
Methods for redirects and template rendering.
358
359
```javascript { .api }
360
/**
361
* Redirect to URL with optional status code
362
* @param statusCode - Optional HTTP status code (default: 302)
363
* @param url - URL to redirect to
364
*/
365
redirect(url: string): void;
366
redirect(statusCode: number, url: string): void;
367
368
/**
369
* Render template with data
370
* @param view - Template name
371
* @param data - Template data
372
* @param callback - Optional callback
373
*/
374
render(view: string, data?: object, callback?: Function): void;
375
render(view: string, callback?: Function): void;
376
```
377
378
### Other Response Methods
379
380
Additional response utility methods.
381
382
```javascript { .api }
383
/**
384
* Set Location header
385
* @param location - Location URL
386
* @returns Response instance
387
*/
388
location(location: string): MockResponse;
389
390
/**
391
* Add field(s) to Vary response header
392
* @param fields - Field name or array of field names
393
* @returns Response instance
394
*/
395
vary(fields: string | string[]): MockResponse;
396
397
/**
398
* Perform content negotiation
399
* @param supported - Object mapping content types to handler functions
400
* @returns Result of handler function
401
*/
402
format(supported: { [type: string]: Function }): any;
403
404
/**
405
* Set encoding for response data
406
* @param encoding - Character encoding
407
*/
408
setEncoding(encoding: string): void;
409
410
/**
411
* Get current encoding
412
* @returns Current encoding
413
*/
414
getEncoding(): string;
415
416
/**
417
* Destroy the response stream
418
* @param args - Optional arguments passed to destroy
419
*/
420
destroy(...args: any[]): void;
421
422
/**
423
* Destroy the response stream soon
424
* @param args - Optional arguments passed to destroySoon
425
*/
426
destroySoon(...args: any[]): void;
427
```
428
429
### Introspection Methods
430
431
Testing utility methods for verifying response behavior (prefixed with `_`).
432
433
```javascript { .api }
434
/**
435
* Check if end() has been called
436
* @returns True if end() was called
437
*/
438
_isEndCalled(): boolean;
439
440
/**
441
* Get all response headers
442
* @returns Headers object
443
*/
444
_getHeaders(): object;
445
446
/**
447
* Get response data as string
448
* @returns Response data
449
*/
450
_getData(): string;
451
452
/**
453
* Get response data as parsed JSON
454
* @returns Parsed JSON data
455
*/
456
_getJSONData(): any;
457
458
/**
459
* Get response data as Buffer
460
* @returns Response buffer
461
*/
462
_getBuffer(): Buffer;
463
464
/**
465
* Get array of written chunks
466
* @returns Array of data chunks written to response
467
*/
468
_getChunks(): any[];
469
470
/**
471
* Get response locals
472
* @returns Locals object
473
*/
474
_getLocals(): object;
475
476
/**
477
* Get response status code
478
* @returns Status code
479
*/
480
_getStatusCode(): number;
481
482
/**
483
* Get response status message
484
* @returns Status message
485
*/
486
_getStatusMessage(): string;
487
488
/**
489
* Check if response is JSON
490
* @returns True if Content-Type is application/json
491
*/
492
_isJSON(): boolean;
493
494
/**
495
* Check if response encoding is UTF-8
496
* @returns True if encoding is utf8
497
*/
498
_isUTF8(): boolean;
499
500
/**
501
* Validate Content-Length header against actual data length
502
* @returns True if Content-Length matches data length
503
*/
504
_isDataLengthValid(): boolean;
505
506
/**
507
* Get redirect URL (if redirect was called)
508
* @returns Redirect URL
509
*/
510
_getRedirectUrl(): string;
511
512
/**
513
* Get render view name (if render was called)
514
* @returns View name
515
*/
516
_getRenderView(): string;
517
518
/**
519
* Get render data (if render was called)
520
* @returns Render data
521
*/
522
_getRenderData(): object;
523
```
524
525
**Usage Examples:**
526
527
```javascript
528
const response = httpMocks.createResponse();
529
530
// Use the response in your handler
531
yourRouteHandler(request, response);
532
533
// Verify the response in tests
534
console.log(response._isEndCalled()); // true if end() was called
535
console.log(response._getStatusCode()); // e.g., 200
536
console.log(response._getData()); // response body as string
537
console.log(response._getJSONData()); // parsed JSON if JSON response
538
console.log(response._isJSON()); // true if JSON response
539
console.log(response._getHeaders()); // all response headers
540
541
// Check redirects
542
if (response.statusCode === 302) {
543
console.log(response._getRedirectUrl()); // redirect URL
544
}
545
546
// Check renders
547
console.log(response._getRenderView()); // template name
548
console.log(response._getRenderData()); // template data
549
```
550
551
## Response Properties
552
553
The mock response includes all standard HTTP response properties:
554
555
- **statusCode** (number): HTTP status code (default: 200)
556
- **statusMessage** (string): HTTP status message (default: 'OK')
557
- **headersSent** (boolean): Whether headers have been sent
558
- **finished** (boolean): Whether response is finished
559
- **writableEnded** (boolean): Whether response ended
560
- **writableFinished** (boolean): Whether response finished writing
561
- **cookies** (object): Response cookies with values and options
562
- **locals** (object): Response local variables (Express-style)