Mock HTTP objects for testing Express, Next.js, and Koa routing functions
npx @tessl/cli install tessl/npm-node-mocks-http@1.17.00
# node-mocks-http
1
2
node-mocks-http provides comprehensive mock implementations of Node.js HTTP request and response objects specifically designed for testing web server applications built with Express, Next.js, and Koa frameworks. It offers full-featured mock objects that simulate real HTTP requests and responses, including support for headers, cookies, parameters, query strings, request bodies, and all standard HTTP methods.
3
4
## Package Information
5
6
- **Package Name**: node-mocks-http
7
- **Package Type**: npm
8
- **Language**: JavaScript with TypeScript definitions
9
- **Installation**: `npm install node-mocks-http --save-dev`
10
11
## Core Imports
12
13
```javascript
14
const httpMocks = require('node-mocks-http');
15
```
16
17
For ESM:
18
19
```javascript
20
import httpMocks from 'node-mocks-http';
21
```
22
23
TypeScript:
24
25
```typescript
26
import * as httpMocks from 'node-mocks-http';
27
import { createRequest, createResponse, createMocks } from 'node-mocks-http';
28
```
29
30
## Basic Usage
31
32
```javascript
33
const httpMocks = require('node-mocks-http');
34
35
// Create individual mocks
36
const request = httpMocks.createRequest({
37
method: 'GET',
38
url: '/user/42',
39
params: { id: 42 },
40
headers: { 'Content-Type': 'application/json' }
41
});
42
43
const response = httpMocks.createResponse();
44
45
// Or create linked request/response pair
46
const { req, res } = httpMocks.createMocks({
47
method: 'POST',
48
url: '/api/users',
49
body: { name: 'John', email: 'john@example.com' }
50
});
51
52
// Use in your tests
53
yourRouteHandler(req, res);
54
55
// Verify results
56
console.log(res.statusCode); // 200
57
console.log(res._getData()); // Response data
58
console.log(res._isJSON()); // true if JSON response
59
```
60
61
## Architecture
62
63
node-mocks-http is built around several key components:
64
65
- **Mock Request**: Complete HTTP request simulation with headers, body, params, and Express-style methods
66
- **Mock Response**: Full HTTP response functionality with status codes, headers, cookies, and content methods
67
- **Express Integration**: Specialized mocks that extend base functionality for Express-specific features
68
- **TypeScript Support**: Generic type support for different frameworks (Express, Next.js, etc.)
69
- **Introspection Methods**: Testing utilities prefixed with `_` for verifying mock behavior
70
71
## Capabilities
72
73
### Request Mocking
74
75
Complete HTTP request object simulation with all standard properties and methods. Perfect for testing route handlers, middleware, and request processing logic.
76
77
```javascript { .api }
78
function createRequest<T extends RequestType = Request>(options?: RequestOptions): MockRequest<T>;
79
80
interface RequestOptions {
81
method?: RequestMethod;
82
url?: string;
83
originalUrl?: string;
84
baseUrl?: string;
85
path?: string;
86
params?: Params;
87
session?: Session;
88
cookies?: Cookies;
89
signedCookies?: Cookies;
90
headers?: Headers;
91
body?: Body;
92
query?: Query;
93
files?: Files;
94
ip?: string;
95
[key: string]: any;
96
}
97
```
98
99
[Request Mocking](./request-mocking.md)
100
101
### Response Mocking
102
103
Full HTTP response object simulation with status codes, headers, cookies, and all response methods. Includes introspection methods for test verification.
104
105
```javascript { .api }
106
function createResponse<T extends ResponseType = Response>(options?: ResponseOptions): MockResponse<T>;
107
108
interface ResponseOptions {
109
eventEmitter?: any;
110
writableStream?: any;
111
req?: any;
112
locals?: any;
113
}
114
```
115
116
[Response Mocking](./response-mocking.md)
117
118
### Mock Creation Utilities
119
120
Convenient functions for creating individual mocks or linked request/response pairs that can interact with each other.
121
122
```javascript { .api }
123
function createMocks<T1 extends RequestType = Request, T2 extends ResponseType = Response>(
124
reqOptions?: RequestOptions,
125
resOptions?: ResponseOptions
126
): Mocks<T1, T2>;
127
128
interface Mocks<T1 extends RequestType, T2 extends ResponseType> {
129
req: MockRequest<T1>;
130
res: MockResponse<T2>;
131
}
132
```
133
134
[Mock Creation](./mock-creation.md)
135
136
### Express Integration
137
138
Enhanced mocks with Express-specific functionality including application mocking, Express request/response extensions, and routing utilities.
139
140
```javascript { .api }
141
const express = httpMocks.express;
142
function createApplication(): ExpressApplication;
143
```
144
145
[Express Integration](./express-integration.md)
146
147
## Types
148
149
```typescript { .api }
150
type RequestMethod = 'CONNECT' | 'DELETE' | 'GET' | 'HEAD' | 'OPTIONS' | 'PATCH' | 'POST' | 'PUT' | 'TRACE';
151
type RequestType = IncomingMessage | globalThis.Request;
152
type ResponseType = OutgoingMessage | globalThis.Response;
153
154
interface Params {
155
[key: string]: any;
156
}
157
158
interface Session {
159
[key: string]: any;
160
}
161
162
interface Cookies {
163
[key: string]: string;
164
}
165
166
interface Headers {
167
// Standard HTTP headers
168
accept?: string;
169
'accept-language'?: string;
170
'accept-patch'?: string;
171
'accept-ranges'?: string;
172
'access-control-allow-credentials'?: string;
173
'access-control-allow-headers'?: string;
174
'access-control-allow-methods'?: string;
175
'access-control-allow-origin'?: string;
176
'access-control-expose-headers'?: string;
177
'access-control-max-age'?: string;
178
age?: string;
179
allow?: string;
180
'alt-svc'?: string;
181
authorization?: string;
182
'cache-control'?: string;
183
connection?: string;
184
'content-disposition'?: string;
185
'content-encoding'?: string;
186
'content-language'?: string;
187
'content-length'?: string;
188
'content-location'?: string;
189
'content-range'?: string;
190
'content-type'?: string;
191
cookie?: string;
192
date?: string;
193
expect?: string;
194
expires?: string;
195
forwarded?: string;
196
from?: string;
197
host?: string;
198
'if-match'?: string;
199
'if-modified-since'?: string;
200
'if-none-match'?: string;
201
'if-unmodified-since'?: string;
202
'last-modified'?: string;
203
location?: string;
204
pragma?: string;
205
'proxy-authenticate'?: string;
206
'proxy-authorization'?: string;
207
'public-key-pins'?: string;
208
range?: string;
209
referer?: string;
210
'retry-after'?: string;
211
'set-cookie'?: string[];
212
'strict-transport-security'?: string;
213
tk?: string;
214
trailer?: string;
215
'transfer-encoding'?: string;
216
upgrade?: string;
217
'user-agent'?: string;
218
vary?: string;
219
via?: string;
220
warning?: string;
221
'www-authenticate'?: string;
222
223
// Support for arbitrary headers
224
[header: string]: string | string[] | undefined;
225
}
226
227
interface HeaderWebAPI {
228
// Include all header properties
229
[header: string]: any;
230
231
// Web API Headers methods
232
append(name: string, value: string): void;
233
delete(name: string): void;
234
get(name: string): string | null;
235
has(name: string): boolean;
236
set(name: string, value: string): void;
237
forEach(callbackfn: (value: string, key: string, parent: HeaderWebAPI) => void, thisArg?: any): void;
238
239
// Iterator methods
240
entries(): IterableIterator<[string, string]>;
241
keys(): IterableIterator<string>;
242
values(): IterableIterator<string>;
243
[Symbol.iterator](): IterableIterator<[string, string]>;
244
}
245
246
interface Query {
247
[key: string]: any;
248
}
249
250
interface Files {
251
[key: string]: string;
252
}
253
254
interface Body {
255
[key: string]: any;
256
}
257
258
interface ResponseCookie {
259
value: any;
260
options: CookieOptions;
261
}
262
```