0
# Express Integration
1
2
Enhanced mocks with Express-specific functionality including application mocking, Express request/response extensions, and routing utilities for comprehensive Express application testing.
3
4
## Capabilities
5
6
### Express Application Mock
7
8
Create mock Express applications for testing application-level functionality.
9
10
```javascript { .api }
11
/**
12
* Access Express-specific mock functionality
13
*/
14
const express = httpMocks.express;
15
16
/**
17
* Create a mock Express application
18
* @returns Mock Express application with standard Express methods
19
*/
20
function createApplication(): ExpressApplication;
21
22
interface ExpressApplication {
23
// Configuration methods
24
init(): void;
25
defaultConfiguration(): void;
26
set(setting: string, value?: any): any;
27
get(setting: string): any;
28
enabled(setting: string): boolean;
29
disabled(setting: string): boolean;
30
enable(setting: string): ExpressApplication;
31
disable(setting: string): ExpressApplication;
32
33
// Routing methods (stubs)
34
use(...args: any[]): ExpressApplication;
35
route(path: string): any;
36
param(name: string, handler: Function): ExpressApplication;
37
all(path: string, ...handlers: Function[]): ExpressApplication;
38
lazyrouter(): void;
39
handle(req: any, res: any, next?: Function): void;
40
41
// HTTP method handlers (stubs) - includes all HTTP methods
42
get(path: string, ...handlers: Function[]): ExpressApplication;
43
post(path: string, ...handlers: Function[]): ExpressApplication;
44
put(path: string, ...handlers: Function[]): ExpressApplication;
45
delete(path: string, ...handlers: Function[]): ExpressApplication;
46
del(path: string, ...handlers: Function[]): ExpressApplication; // deprecated alias
47
patch(path: string, ...handlers: Function[]): ExpressApplication;
48
head(path: string, ...handlers: Function[]): ExpressApplication;
49
options(path: string, ...handlers: Function[]): ExpressApplication;
50
connect(path: string, ...handlers: Function[]): ExpressApplication;
51
trace(path: string, ...handlers: Function[]): ExpressApplication;
52
53
// Template and other methods
54
engine(ext: string, fn: Function): ExpressApplication;
55
render(name: string, options?: any, callback?: Function): void;
56
listen(...args: any[]): any;
57
path(): string;
58
59
// Application properties
60
locals: any;
61
mountpath: string;
62
settings: any;
63
request: any;
64
response: any;
65
}
66
```
67
68
**Usage Examples:**
69
70
```javascript
71
const httpMocks = require('node-mocks-http');
72
73
// Create mock Express app
74
const app = httpMocks.express.createApplication();
75
76
// Configure app settings
77
app.set('view engine', 'ejs');
78
app.set('port', 3000);
79
app.enable('trust proxy');
80
81
console.log(app.get('view engine')); // 'ejs'
82
console.log(app.enabled('trust proxy')); // true
83
84
// Set locals
85
app.locals.title = 'My App';
86
app.locals.settings = { theme: 'dark' };
87
88
// Initialize with default Express configuration
89
app.init();
90
app.defaultConfiguration();
91
92
// Mock routing (methods return app for chaining but don't actually route)
93
app.use('/api', middlewareFunction);
94
app.get('/users', userHandler);
95
app.post('/users', createUserHandler);
96
97
// Additional HTTP methods supported
98
app.put('/users/:id', updateUserHandler);
99
app.patch('/users/:id', patchUserHandler);
100
app.delete('/users/:id', deleteUserHandler);
101
app.del('/users/:id', deleteUserHandler); // deprecated alias
102
```
103
104
### Express Request Extensions
105
106
Enhanced request mocking with Express-specific methods and properties.
107
108
```javascript { .api }
109
/**
110
* Express request prototype with additional methods
111
*/
112
const expressRequest = httpMocks.express.request;
113
114
interface ExpressRequestExtensions {
115
// Enhanced header access (handles Referer/Referrer aliasing)
116
header(name: string): string | undefined;
117
get(name: string): string | undefined;
118
119
// Content negotiation
120
accepts(...types: string[]): string | false;
121
acceptsEncodings(...encodings: string[]): string | false;
122
acceptsEncoding(...encodings: string[]): string | false;
123
acceptsCharsets(...charsets: string[]): string | false;
124
acceptsCharset(...charsets: string[]): string | false;
125
acceptsLanguages(...languages: string[]): string | false;
126
acceptsLanguage(...languages: string[]): string | false;
127
128
// Other Express methods
129
range(size: number): any;
130
param(name: string, defaultValue?: any): any;
131
is(...types: string[]): string | false | null;
132
133
// Express properties (getters)
134
protocol: string;
135
secure: boolean;
136
ip: string;
137
ips: string[];
138
subdomains: string[];
139
path: string;
140
hostname: string;
141
host: string;
142
fresh: boolean;
143
stale: boolean;
144
xhr: boolean;
145
}
146
```
147
148
**Usage Examples:**
149
150
```javascript
151
// Express request mock with enhanced functionality
152
const req = httpMocks.createRequest({
153
headers: {
154
'Host': 'example.com',
155
'X-Forwarded-Proto': 'https',
156
'Accept': 'text/html,application/json',
157
'Referer': 'https://google.com'
158
},
159
ip: '192.168.1.100'
160
});
161
162
// Express-specific properties
163
console.log(req.protocol); // 'https'
164
console.log(req.secure); // true
165
console.log(req.hostname); // 'example.com'
166
console.log(req.ip); // '192.168.1.100'
167
168
// Enhanced header access
169
console.log(req.get('referrer')); // 'https://google.com' (aliased from Referer)
170
171
// Content negotiation
172
console.log(req.accepts(['json', 'html'])); // 'html' (first match from Accept header)
173
```
174
175
### Express Response Extensions
176
177
Enhanced response mocking with Express-specific methods.
178
179
```javascript { .api }
180
/**
181
* Express response prototype with additional methods
182
*/
183
const expressResponse = httpMocks.express.response;
184
185
// All standard MockResponse methods plus Express-specific enhancements
186
// (Most Express response functionality is already included in the base MockResponse)
187
```
188
189
### Express Application Testing Patterns
190
191
Common patterns for testing Express applications with mock objects.
192
193
**Testing Application Configuration:**
194
195
```javascript
196
const httpMocks = require('node-mocks-http');
197
198
function configureApp(app) {
199
app.set('view engine', 'pug');
200
app.set('views', './views');
201
app.enable('trust proxy');
202
app.disable('x-powered-by');
203
204
app.locals.siteName = 'My Website';
205
app.locals.version = '1.0.0';
206
}
207
208
// Test configuration
209
const app = httpMocks.express.createApplication();
210
configureApp(app);
211
212
// Verify configuration
213
console.log(app.get('view engine')); // 'pug'
214
console.log(app.enabled('trust proxy')); // true
215
console.log(app.disabled('x-powered-by')); // true
216
console.log(app.locals.siteName); // 'My Website'
217
```
218
219
**Testing Middleware:**
220
221
```javascript
222
function authMiddleware(req, res, next) {
223
const token = req.get('Authorization');
224
225
if (!token) {
226
return res.status(401).json({ error: 'No token provided' });
227
}
228
229
// Verify token (simplified)
230
if (token === 'Bearer valid-token') {
231
req.user = { id: 1, name: 'John Doe' };
232
next();
233
} else {
234
res.status(403).json({ error: 'Invalid token' });
235
}
236
}
237
238
// Test middleware with valid token
239
const { req, res } = httpMocks.createMocks({
240
headers: { 'Authorization': 'Bearer valid-token' }
241
});
242
243
const next = jest.fn();
244
authMiddleware(req, res, next);
245
246
console.log(req.user); // { id: 1, name: 'John Doe' }
247
console.log(next).toHaveBeenCalled(); // true
248
249
// Test middleware with invalid token
250
const { req: badReq, res: badRes } = httpMocks.createMocks({
251
headers: { 'Authorization': 'Bearer invalid-token' }
252
});
253
254
authMiddleware(badReq, badRes, next);
255
256
console.log(badRes._getStatusCode()); // 403
257
console.log(badRes._getJSONData()); // { error: 'Invalid token' }
258
```
259
260
**Testing Route Handlers:**
261
262
```javascript
263
function getUserHandler(req, res) {
264
const userId = req.params.id;
265
266
// Simulate database lookup
267
const user = findUserById(userId);
268
269
if (!user) {
270
return res.status(404).json({ error: 'User not found' });
271
}
272
273
// Use content negotiation
274
res.format({
275
'application/json': () => res.json(user),
276
'text/html': () => res.render('user', { user }),
277
'default': () => res.status(406).send('Not Acceptable')
278
});
279
}
280
281
// Test JSON response
282
const { req, res } = httpMocks.createMocks({
283
params: { id: '123' },
284
headers: { 'Accept': 'application/json' }
285
});
286
287
getUserHandler(req, res);
288
289
console.log(res._getStatusCode()); // 200
290
console.log(res._isJSON()); // true
291
console.log(res._getJSONData()); // user object
292
293
// Test HTML response
294
const { req: htmlReq, res: htmlRes } = httpMocks.createMocks({
295
params: { id: '123' },
296
headers: { 'Accept': 'text/html' }
297
});
298
299
getUserHandler(htmlReq, htmlRes);
300
301
console.log(htmlRes._getRenderView()); // 'user'
302
console.log(htmlRes._getRenderData()); // { user: ... }
303
```
304
305
**Testing Error Handling:**
306
307
```javascript
308
function errorMiddleware(err, req, res, next) {
309
const isDevelopment = req.app.get('env') === 'development';
310
311
const errorResponse = {
312
message: err.message,
313
status: err.status || 500
314
};
315
316
if (isDevelopment) {
317
errorResponse.stack = err.stack;
318
}
319
320
res.status(errorResponse.status).json(errorResponse);
321
}
322
323
// Test error middleware
324
const app = httpMocks.express.createApplication();
325
app.set('env', 'development');
326
327
const { req, res } = httpMocks.createMocks();
328
req.app = app; // Link request to app
329
330
const error = new Error('Test error');
331
error.status = 400;
332
333
errorMiddleware(error, req, res, () => {});
334
335
console.log(res._getStatusCode()); // 400
336
const errorData = res._getJSONData();
337
console.log(errorData.message); // 'Test error'
338
console.log(errorData.stack); // Error stack (because development mode)
339
```
340
341
### Express Integration Properties
342
343
Properties available when using Express integration:
344
345
**Application Properties:**
346
- **locals** (object): Application-wide local variables
347
- **mountpath** (string): Mount path of the application
348
- **settings** (object): Application settings
349
- **request** (object): Request prototype
350
- **response** (object): Response prototype
351
352
**Request Properties (additional to base mock):**
353
- **app** (object): Reference to Express application
354
- **protocol** (string): Request protocol (http/https)
355
- **secure** (boolean): Whether connection is secure
356
- **hostname** (string): Request hostname
357
- **host** (string): Request host with port
358
- **fresh** (boolean): Whether request is fresh
359
- **stale** (boolean): Whether request is stale
360
- **xhr** (boolean): Whether request is XMLHttpRequest
361
362
**Response Properties (additional to base mock):**
363
- **app** (object): Reference to Express application
364
365
### Advanced Express Testing
366
367
**Testing Route Parameters:**
368
369
```javascript
370
function userProfileHandler(req, res) {
371
const { userId, section } = req.params;
372
373
if (!userId || !section) {
374
return res.status(400).json({ error: 'Missing parameters' });
375
}
376
377
const profile = getUserProfile(userId, section);
378
res.json(profile);
379
}
380
381
// Test with route parameters
382
const { req, res } = httpMocks.createMocks({
383
method: 'GET',
384
url: '/users/123/profile',
385
params: { userId: '123', section: 'profile' }
386
});
387
388
userProfileHandler(req, res);
389
390
console.log(res._getStatusCode()); // 200
391
console.log(res._getJSONData()); // profile data
392
```
393
394
**Testing Query Parameters:**
395
396
```javascript
397
function searchHandler(req, res) {
398
const { q, limit = 10, offset = 0 } = req.query;
399
400
if (!q) {
401
return res.status(400).json({ error: 'Query parameter required' });
402
}
403
404
const results = searchDatabase(q, parseInt(limit), parseInt(offset));
405
res.json({ results, total: results.length });
406
}
407
408
// Test with query parameters
409
const { req, res } = httpMocks.createMocks({
410
method: 'GET',
411
url: '/search?q=node&limit=5',
412
query: { q: 'node', limit: '5' }
413
});
414
415
searchHandler(req, res);
416
417
console.log(res._getJSONData()); // { results: [...], total: 5 }
418
```