0
# Mock Creation
1
2
Convenient functions for creating individual mocks or linked request/response pairs that can interact with each other, with full TypeScript support for different frameworks.
3
4
## Capabilities
5
6
### Create Linked Mocks
7
8
Creates linked request and response objects that can interact with each other, essential for testing functionality that requires both objects.
9
10
```javascript { .api }
11
/**
12
* Creates linked request and response mocks that can interact
13
* @param reqOptions - Options for request creation
14
* @param resOptions - Options for response creation
15
* @returns Object containing both req and res mocks
16
*/
17
function createMocks<T1 extends RequestType = Request, T2 extends ResponseType = Response>(
18
reqOptions?: RequestOptions,
19
resOptions?: ResponseOptions
20
): Mocks<T1, T2>;
21
22
interface Mocks<T1 extends RequestType, T2 extends ResponseType> {
23
req: MockRequest<T1>;
24
res: MockResponse<T2>;
25
}
26
```
27
28
**Usage Examples:**
29
30
```javascript
31
const httpMocks = require('node-mocks-http');
32
33
// Basic linked mocks
34
const { req, res } = httpMocks.createMocks();
35
36
// Linked mocks with configuration
37
const { req, res } = httpMocks.createMocks({
38
method: 'POST',
39
url: '/api/users',
40
headers: { 'Content-Type': 'application/json' },
41
body: { name: 'John', email: 'john@example.com' }
42
}, {
43
locals: { user: { id: 1 } }
44
});
45
46
// Use in route handler that needs both objects
47
yourRouteHandler(req, res);
48
49
// The response can use the request for content negotiation
50
res.format({
51
'text/html': () => res.send('<h1>Hello</h1>'),
52
'application/json': () => res.json({ message: 'Hello' })
53
});
54
```
55
56
### TypeScript Generic Support
57
58
Full TypeScript integration with generic type parameters for different frameworks.
59
60
```typescript { .api }
61
// Express types (default)
62
const { req, res } = httpMocks.createMocks<Express.Request, Express.Response>();
63
64
// Next.js API routes
65
const { req, res } = httpMocks.createMocks<NextApiRequest, NextApiResponse>();
66
67
// Next.js App Router
68
const { req, res } = httpMocks.createMocks<NextRequest, NextResponse>();
69
70
// Custom types extending base HTTP types
71
interface CustomRequest extends IncomingMessage {
72
user?: { id: number; name: string };
73
}
74
75
const { req, res } = httpMocks.createMocks<CustomRequest, ServerResponse>();
76
```
77
78
**Usage Examples:**
79
80
```typescript
81
import * as httpMocks from 'node-mocks-http';
82
import { NextApiRequest, NextApiResponse } from 'next';
83
84
// Next.js API route testing
85
const { req, res } = httpMocks.createMocks<NextApiRequest, NextApiResponse>({
86
method: 'GET',
87
query: { id: '123' }
88
});
89
90
// Type-safe access to Next.js specific properties
91
console.log(req.query.id); // TypeScript knows this is a string | string[]
92
93
// Express route testing
94
import { Request, Response } from 'express';
95
96
const { req, res } = httpMocks.createMocks<Request, Response>({
97
method: 'POST',
98
body: { data: 'test' },
99
params: { userId: '456' }
100
});
101
102
// Type-safe Express properties
103
console.log(req.params.userId); // string
104
console.log(req.body.data); // any (but known structure)
105
```
106
107
### Individual Mock Creation
108
109
While `createMocks()` is convenient, you can also create individual mocks when you only need one or the other.
110
111
```javascript { .api }
112
// Import individual creation functions
113
const { createRequest, createResponse } = require('node-mocks-http');
114
115
// Create only request
116
const request = createRequest({
117
method: 'GET',
118
url: '/api/data'
119
});
120
121
// Create only response
122
const response = createResponse({
123
locals: { theme: 'dark' }
124
});
125
```
126
127
### Mock Interaction Patterns
128
129
When mocks are created together with `createMocks()`, they can interact in ways that individual mocks cannot.
130
131
**Content Negotiation:**
132
133
```javascript
134
const { req, res } = httpMocks.createMocks({
135
headers: { 'Accept': 'application/json' }
136
});
137
138
// The response can access the request's Accept header
139
res.format({
140
'text/html': () => res.send('<h1>Data</h1>'),
141
'application/json': () => res.json({ data: 'value' }),
142
'default': () => res.status(406).send('Not Acceptable')
143
});
144
145
// Result: JSON response because request accepts JSON
146
console.log(res._isJSON()); // true
147
console.log(res._getJSONData()); // { data: 'value' }
148
```
149
150
**Session Sharing:**
151
152
```javascript
153
const { req, res } = httpMocks.createMocks({
154
session: { userId: 123, isAuthenticated: true }
155
});
156
157
// Both request and response can access the same session
158
console.log(req.session.userId); // 123
159
// Session can be modified during request processing
160
req.session.lastAccess = new Date();
161
```
162
163
### Configuration Options
164
165
Detailed configuration options for both request and response creation.
166
167
```javascript { .api }
168
// Request configuration options
169
const requestOptions = {
170
method: 'POST', // HTTP method
171
url: '/api/endpoint', // Request URL
172
originalUrl: '/api/endpoint', // Original URL before rewriting
173
baseUrl: '/api', // Base URL portion
174
path: '/endpoint', // Path portion
175
params: { id: '123' }, // Route parameters
176
query: { sort: 'asc' }, // Query string parameters
177
headers: { // HTTP headers
178
'Content-Type': 'application/json',
179
'Authorization': 'Bearer token'
180
},
181
body: { data: 'payload' }, // Request body
182
cookies: { sessionId: 'abc' }, // Cookies
183
signedCookies: { userId: '123' }, // Signed cookies
184
session: { authenticated: true }, // Session data
185
files: { upload: 'file.txt' }, // File uploads
186
ip: '192.168.1.1', // Client IP
187
// Any additional custom properties
188
customProperty: 'value'
189
};
190
191
// Response configuration options
192
const responseOptions = {
193
eventEmitter: customEmitter, // Custom event emitter
194
writableStream: customStream, // Custom writable stream
195
req: requestObject, // Associated request object
196
locals: { // Response local variables
197
user: { id: 1, name: 'John' },
198
settings: { theme: 'dark' }
199
}
200
};
201
202
const { req, res } = httpMocks.createMocks(requestOptions, responseOptions);
203
```
204
205
### Advanced Usage Patterns
206
207
**Testing Middleware:**
208
209
```javascript
210
function testMiddleware(req, res, next) {
211
if (!req.headers.authorization) {
212
return res.status(401).json({ error: 'Unauthorized' });
213
}
214
req.user = { id: 1, name: 'John' };
215
next();
216
}
217
218
// Test the middleware
219
const { req, res } = httpMocks.createMocks({
220
headers: { authorization: 'Bearer token123' }
221
});
222
223
const next = jest.fn();
224
testMiddleware(req, res, next);
225
226
// Verify middleware behavior
227
console.log(req.user); // { id: 1, name: 'John' }
228
console.log(next.called); // true
229
console.log(res._getStatusCode()); // 200 (not 401)
230
```
231
232
**Testing Route Handlers:**
233
234
```javascript
235
function userHandler(req, res) {
236
const userId = req.params.id;
237
const user = getUserById(userId);
238
239
if (!user) {
240
return res.status(404).json({ error: 'User not found' });
241
}
242
243
res.json(user);
244
}
245
246
// Test the handler
247
const { req, res } = httpMocks.createMocks({
248
method: 'GET',
249
url: '/users/123',
250
params: { id: '123' }
251
});
252
253
userHandler(req, res);
254
255
// Verify handler behavior
256
console.log(res._getStatusCode()); // 200 or 404
257
console.log(res._isJSON()); // true
258
console.log(res._getJSONData()); // user object or error
259
```
260
261
**Testing File Uploads:**
262
263
```javascript
264
const { req, res } = httpMocks.createMocks({
265
method: 'POST',
266
url: '/upload',
267
headers: { 'Content-Type': 'multipart/form-data' },
268
files: {
269
document: 'uploaded-file.pdf',
270
image: 'photo.jpg'
271
},
272
body: {
273
title: 'My Upload',
274
description: 'File description'
275
}
276
});
277
278
uploadHandler(req, res);
279
280
// Access uploaded files
281
console.log(req.files.document); // 'uploaded-file.pdf'
282
console.log(req.body.title); // 'My Upload'
283
```
284
285
## Integration Examples
286
287
Examples of using mock creation with popular testing frameworks:
288
289
**Jest:**
290
291
```javascript
292
describe('User API', () => {
293
test('should create user successfully', () => {
294
const { req, res } = httpMocks.createMocks({
295
method: 'POST',
296
body: { name: 'John', email: 'john@example.com' }
297
});
298
299
createUserHandler(req, res);
300
301
expect(res._getStatusCode()).toBe(201);
302
expect(res._isJSON()).toBe(true);
303
expect(res._getJSONData()).toMatchObject({
304
id: expect.any(Number),
305
name: 'John',
306
email: 'john@example.com'
307
});
308
});
309
});
310
```
311
312
**Mocha:**
313
314
```javascript
315
describe('Authentication', () => {
316
it('should reject unauthenticated requests', () => {
317
const { req, res } = httpMocks.createMocks({
318
method: 'GET',
319
url: '/protected'
320
});
321
322
authMiddleware(req, res, () => {});
323
324
expect(res._getStatusCode()).to.equal(401);
325
expect(res._getJSONData()).to.have.property('error');
326
});
327
});
328
```