0
# Request and Response Objects
1
2
The MockRequest and MockResponse classes provide complete control over HTTP request inspection and response construction. These objects follow a fluent API pattern where methods can be chained together.
3
4
## Capabilities
5
6
### MockRequest Class
7
8
Represents an incoming HTTP request with methods to inspect and modify request properties.
9
10
```typescript { .api }
11
class MockRequest {
12
/**
13
* Get the HTTP method
14
* @returns The HTTP method (e.g., 'GET', 'POST')
15
*/
16
method(): string;
17
18
/**
19
* Set the HTTP method
20
* @param method - HTTP method to set
21
* @returns MockRequest instance for chaining
22
*/
23
method(method: string): MockRequest;
24
25
/**
26
* Get the request URL as a parsed object
27
* @returns MockURL object with parsed URL components
28
*/
29
url(): MockURL;
30
31
/**
32
* Set the request URL
33
* @param url - URL string to parse and set
34
* @returns MockRequest instance for chaining
35
*/
36
url(url: string): MockRequest;
37
38
/**
39
* Get a specific request header value
40
* @param name - Header name (case-insensitive)
41
* @returns Header value or null if not found
42
*/
43
header(name: string): null | string;
44
45
/**
46
* Set a request header
47
* @param name - Header name
48
* @param value - Header value
49
* @returns MockRequest instance for chaining
50
*/
51
header(name: string, value: string): MockRequest;
52
53
/**
54
* Get all request headers
55
* @returns Object containing all headers
56
*/
57
headers(): MockHeaders;
58
59
/**
60
* Set multiple request headers
61
* @param headers - Object containing header name-value pairs
62
* @returns MockRequest instance for chaining
63
*/
64
headers(headers: MockHeaders): MockRequest;
65
66
/**
67
* Get the request body
68
* @returns Request body (any type)
69
*/
70
body(): any;
71
72
/**
73
* Set the request body
74
* @param body - Request body content
75
* @returns MockRequest instance for chaining
76
*/
77
body(body: any): MockRequest;
78
}
79
```
80
81
**Usage Examples:**
82
83
```typescript
84
mock.post('/api/users', (req, res) => {
85
// Inspect request method
86
console.log(req.method()); // 'POST'
87
88
// Check request headers
89
const contentType = req.header('Content-Type');
90
if (contentType === 'application/json') {
91
// Parse JSON body
92
const userData = JSON.parse(req.body());
93
console.log('User data:', userData);
94
}
95
96
// Check URL components
97
const url = req.url();
98
console.log('Path:', url.path);
99
console.log('Query params:', url.query);
100
101
// Return response
102
return res.status(201).body(JSON.stringify({ id: 123, ...userData }));
103
});
104
```
105
106
### MockResponse Class
107
108
Represents an HTTP response with methods to set status, headers, and body content.
109
110
```typescript { .api }
111
class MockResponse {
112
/**
113
* Get the response status code
114
* @returns HTTP status code
115
*/
116
status(): number;
117
118
/**
119
* Set the response status code
120
* @param status - HTTP status code (e.g., 200, 404, 500)
121
* @returns MockResponse instance for chaining
122
*/
123
status(status: number): MockResponse;
124
125
/**
126
* Get the response reason phrase
127
* @returns HTTP reason phrase (e.g., 'OK', 'Not Found')
128
*/
129
reason(): string;
130
131
/**
132
* Set the response reason phrase
133
* @param reason - HTTP reason phrase
134
* @returns MockResponse instance for chaining
135
*/
136
reason(reason: string): MockResponse;
137
138
/**
139
* Get a specific response header value
140
* @param name - Header name (case-insensitive)
141
* @returns Header value or null if not found
142
*/
143
header(name: string): null | string;
144
145
/**
146
* Set a response header
147
* @param name - Header name
148
* @param value - Header value
149
* @returns MockResponse instance for chaining
150
*/
151
header(name: string, value: string): MockResponse;
152
153
/**
154
* Get all response headers
155
* @returns Object containing all headers
156
*/
157
headers(): MockHeaders;
158
159
/**
160
* Set multiple response headers
161
* @param headers - Object containing header name-value pairs
162
* @returns MockResponse instance for chaining
163
*/
164
headers(headers: MockHeaders): MockResponse;
165
166
/**
167
* Get the response body
168
* @returns Response body (any type)
169
*/
170
body(): any;
171
172
/**
173
* Set the response body
174
* @param body - Response body content
175
* @returns MockResponse instance for chaining
176
*/
177
body(body: any): MockResponse;
178
}
179
```
180
181
**Usage Examples:**
182
183
```typescript
184
// Basic response construction
185
mock.get('/api/status', (req, res) => {
186
return res
187
.status(200)
188
.reason('OK')
189
.header('Content-Type', 'application/json')
190
.body(JSON.stringify({ status: 'healthy' }));
191
});
192
193
// Error response
194
mock.get('/api/forbidden', (req, res) => {
195
return res
196
.status(403)
197
.reason('Forbidden')
198
.header('Content-Type', 'application/json')
199
.body(JSON.stringify({ error: 'Access denied' }));
200
});
201
202
// Multiple headers at once
203
mock.get('/api/data', (req, res) => {
204
return res
205
.status(200)
206
.headers({
207
'Content-Type': 'application/json',
208
'Cache-Control': 'no-cache',
209
'X-API-Version': '1.0'
210
})
211
.body(JSON.stringify({ data: [1, 2, 3] }));
212
});
213
214
// Dynamic response based on request
215
mock.post('/api/echo', (req, res) => {
216
const requestBody = req.body();
217
const contentType = req.header('Content-Type') || 'text/plain';
218
219
return res
220
.status(200)
221
.header('Content-Type', contentType)
222
.body(requestBody);
223
});
224
```
225
226
### Deprecated Methods
227
228
The following MockResponse methods are deprecated:
229
230
```typescript { .api }
231
/**
232
* @deprecated Use reason() instead
233
*/
234
statusText(): null | string;
235
statusText(reason: string): MockResponse;
236
```
237
238
## Supporting Types
239
240
```typescript { .api }
241
type MockHeaders = {[name: string]: string};
242
243
interface MockURL {
244
protocol?: string;
245
username?: string;
246
password?: string;
247
host?: string;
248
port?: number;
249
path?: string;
250
query?: {[name: string]: string};
251
hash?: string;
252
toString(): string;
253
}
254
```
255
256
## Progress Event Simulation
257
258
xhr-mock automatically simulates progress events for both upload and download when appropriate headers and body content are provided:
259
260
**Upload Progress:**
261
```typescript
262
// Set Content-Length header when sending body to trigger upload progress events
263
mock.post('/upload', (req, res) => {
264
// req will have Content-Length header if set by client
265
return res.status(200);
266
});
267
268
// Client code:
269
const xhr = new XMLHttpRequest();
270
xhr.upload.onprogress = (event) => {
271
console.log(`Upload: ${event.loaded}/${event.total} bytes`);
272
};
273
xhr.open('POST', '/upload');
274
xhr.setRequestHeader('Content-Length', '12');
275
xhr.send('Hello World!');
276
```
277
278
**Download Progress:**
279
```typescript
280
// Set Content-Length header in response to trigger download progress events
281
mock.get('/download', (req, res) => {
282
const data = 'Large file content...';
283
return res
284
.status(200)
285
.header('Content-Length', data.length.toString())
286
.body(data);
287
});
288
289
// Client code:
290
const xhr = new XMLHttpRequest();
291
xhr.onprogress = (event) => {
292
console.log(`Download: ${event.loaded}/${event.total} bytes`);
293
};
294
xhr.open('GET', '/download');
295
xhr.send();
296
```