0
# HTTP Server Mocking
1
2
High-level interface for intercepting and responding to HTTP requests with pattern matching, automatic responses, and request history tracking. The fake server provides a complete testing environment for HTTP-based applications.
3
4
## Capabilities
5
6
### Server Creation
7
8
Create a new fake server instance with optional configuration.
9
10
```javascript { .api }
11
/**
12
* @typedef {Object} ServerConfig
13
* @property {boolean} [autoRespond] - Automatically respond to requests after a delay
14
* @property {number} [autoRespondAfter] - Delay in milliseconds for auto-response (default: 10)
15
* @property {boolean} [respondImmediately] - Respond to requests immediately when received
16
* @property {boolean} [fakeHTTPMethods] - Enable HTTP method override via _method parameter
17
* @property {function(string): void} [logger] - Custom logging function
18
* @property {boolean} [unsafeHeadersEnabled] - Allow setting unsafe headers
19
*/
20
21
/**
22
* Create a new fake server instance
23
* @param {ServerConfig} [config] - Optional configuration object
24
* @returns {FakeServer} FakeServer instance
25
*/
26
function create(config) {
27
// Implementation
28
}
29
```
30
31
**Usage Example:**
32
33
```javascript
34
const nise = require("nise");
35
36
const server = nise.fakeServer.create({
37
autoRespond: true,
38
autoRespondAfter: 100
39
});
40
```
41
42
### Response Configuration
43
44
Set up responses for specific request patterns.
45
46
```javascript { .api }
47
/**
48
* @typedef {string|Array|Function} ResponseBody - Response body (string, array, or function)
49
*/
50
51
/**
52
* Configure response for matching requests
53
* @param {string|null} method - HTTP method (GET, POST, etc.) or null for any method
54
* @param {string|RegExp|Function|null} url - URL pattern (string, RegExp, or function) or null for any URL
55
* @param {ResponseBody} body - Response body (string, array, or function)
56
* @returns {void}
57
*/
58
respondWith(method, url, body) {
59
// Implementation
60
}
61
62
/**
63
* Configure response for URL pattern (any method)
64
* @param {string|RegExp|Function} url - URL pattern
65
* @param {ResponseBody} body - Response body
66
* @returns {void}
67
*/
68
respondWith(url, body) {
69
// Implementation
70
}
71
72
/**
73
* Set default response for all requests
74
* @param {ResponseBody} body - Response body
75
* @returns {void}
76
*/
77
respondWith(body) {
78
// Implementation
79
}
80
```
81
82
**Usage Examples:**
83
84
```javascript
85
// Method and URL specific
86
server.respondWith("GET", "/api/users", [
87
200,
88
{ "Content-Type": "application/json" },
89
JSON.stringify([{ id: 1, name: "Alice" }])
90
]);
91
92
// URL pattern matching with RegExp
93
server.respondWith("GET", /\/api\/users\/\d+/, [
94
200,
95
{ "Content-Type": "application/json" },
96
JSON.stringify({ id: 1, name: "Alice" })
97
]);
98
99
// Function-based responses
100
server.respondWith("POST", "/api/users", function(request) {
101
const userData = JSON.parse(request.requestBody);
102
return [201, { "Content-Type": "application/json" }, JSON.stringify({
103
id: Date.now(),
104
...userData
105
})];
106
});
107
108
// Default response
109
server.respondWith([404, {}, "Not Found"]);
110
```
111
112
### Request Processing
113
114
Control when and how requests are processed.
115
116
```javascript { .api }
117
/**
118
* Process all pending requests using configured responses
119
* @returns {void}
120
*/
121
respond() {
122
// Implementation
123
}
124
125
/**
126
* Process all requests immediately, bypassing queue
127
* @returns {void}
128
*/
129
respondAll() {
130
// Implementation
131
}
132
```
133
134
**Usage Example:**
135
136
```javascript
137
// Manual response processing
138
server.autoRespond = false;
139
// ... make requests in application code ...
140
server.respond(); // Process all pending requests
141
```
142
143
### Request History
144
145
Access information about requests made to the fake server.
146
147
```javascript { .api }
148
/**
149
* @typedef {Object} FakeServer - Server properties for request tracking
150
* @property {XMLHttpRequest[]} requests - Array of all XMLHttpRequest objects
151
* @property {number} requestCount - Total number of requests received
152
* @property {boolean} requested - True if any requests have been made
153
* @property {boolean} requestedOnce - True if exactly one request has been made
154
* @property {boolean} requestedTwice - True if exactly two requests have been made
155
* @property {boolean} requestedThrice - True if exactly three requests have been made
156
* @property {XMLHttpRequest|null} firstRequest - Reference to the first request
157
* @property {XMLHttpRequest|null} secondRequest - Reference to the second request
158
* @property {XMLHttpRequest|null} thirdRequest - Reference to the third request
159
* @property {XMLHttpRequest|null} lastRequest - Reference to the most recent request
160
*/
161
162
/**
163
* Get request by index
164
* @param {number} index - Zero-based request index
165
* @returns {XMLHttpRequest|null} XMLHttpRequest object or null
166
*/
167
getRequest(index) {
168
// Implementation
169
}
170
```
171
172
**Usage Example:**
173
174
```javascript
175
// After making requests
176
console.log(`Total requests: ${server.requestCount}`);
177
console.log(`First request URL: ${server.firstRequest && server.firstRequest.url}`);
178
console.log(`Last request method: ${server.lastRequest && server.lastRequest.method}`);
179
180
// Access specific request
181
const thirdRequest = server.getRequest(2);
182
if (thirdRequest) {
183
console.log(`Third request body: ${thirdRequest.requestBody}`);
184
}
185
```
186
187
### Server Lifecycle
188
189
Manage server state and cleanup.
190
191
```javascript { .api }
192
/**
193
* Restore original XMLHttpRequest and clean up
194
* @returns {void}
195
*/
196
restore() {
197
// Implementation
198
}
199
200
/**
201
* Reset server state (both behavior and history)
202
* @returns {void}
203
*/
204
reset() {
205
// Implementation
206
}
207
208
/**
209
* Clear configured responses and request queue
210
* @returns {void}
211
*/
212
resetBehavior() {
213
// Implementation
214
}
215
216
/**
217
* Clear request history and counters
218
* @returns {void}
219
*/
220
resetHistory() {
221
// Implementation
222
}
223
```
224
225
**Usage Example:**
226
227
```javascript
228
// Clean up after tests
229
afterEach(() => {
230
server.reset(); // Clear state for next test
231
});
232
233
after(() => {
234
server.restore(); // Restore original XMLHttpRequest
235
});
236
```
237
238
### Configuration Management
239
240
Update server configuration after creation.
241
242
```javascript { .api }
243
/**
244
* Update server configuration
245
* @param {Partial<ServerConfig>} config - Configuration options to update
246
* @returns {void}
247
*/
248
configure(config) {
249
// Implementation
250
}
251
```
252
253
**Usage Example:**
254
255
```javascript
256
// Change configuration dynamically
257
server.configure({
258
autoRespond: false,
259
logger: console.log
260
});
261
```
262
263
## Advanced Features
264
265
### URL Pattern Matching
266
267
The fake server supports multiple URL matching strategies:
268
269
- **String matching**: Exact URL match
270
- **RegExp matching**: Pattern-based matching with `url.test(requestUrl)`
271
- **Function matching**: Custom matching logic with `url(requestUrl) === true`
272
273
### Response Functions
274
275
Response functions receive the request object and can return dynamic responses:
276
277
```javascript
278
server.respondWith("POST", "/api/echo", function(request) {
279
// Access request properties
280
const method = request.method;
281
const headers = request.requestHeaders;
282
const body = request.requestBody;
283
284
// Return response array
285
return [200, { "Content-Type": "application/json" }, body];
286
});
287
```
288
289
### HTTP Method Override
290
291
When `fakeHTTPMethods` is enabled, the server checks for `_method` parameter in POST requests:
292
293
```javascript
294
server.configure({ fakeHTTPMethods: true });
295
296
// POST request with _method=DELETE will be treated as DELETE
297
server.respondWith("DELETE", "/api/users/1", [204, {}, ""]);
298
```