0
# Ajax Request Mocking
1
2
XMLHttpRequest interception system for mocking HTTP requests and responses, enabling independent frontend development without backend dependencies. Works with popular Ajax libraries like jQuery, Axios, and native fetch.
3
4
## Capabilities
5
6
### Request Mocking
7
8
Mock HTTP requests by URL patterns with optional method specification.
9
10
```javascript { .api }
11
/**
12
* Mock HTTP requests by URL pattern
13
* @param url - Request URL pattern (string or RegExp)
14
* @param template - Response data template
15
* @returns Mock instance for chaining
16
*/
17
Mock.mock(url: string | RegExp, template: any): typeof Mock;
18
19
/**
20
* Mock HTTP requests by URL pattern and method
21
* @param url - Request URL pattern (string or RegExp)
22
* @param method - HTTP method (get, post, put, delete, head, options, patch)
23
* @param template - Response data template or function
24
* @returns Mock instance for chaining
25
*/
26
Mock.mock(url: string | RegExp, method: string, template: any | Function): typeof Mock;
27
```
28
29
**Basic Request Mocking:**
30
31
```javascript
32
// Mock GET request to /api/users
33
Mock.mock('/api/users', {
34
'users|5-10': [{
35
'id|+1': 1,
36
name: '@name',
37
email: '@email',
38
'age|18-65': 1
39
}]
40
});
41
42
// Mock POST request with specific method
43
Mock.mock('/api/users', 'post', {
44
success: true,
45
message: 'User created successfully',
46
id: '@inc'
47
});
48
49
// Mock with RegExp pattern
50
Mock.mock(/\/api\/users\/\d+/, 'get', {
51
id: '@natural(1, 1000)',
52
name: '@name',
53
email: '@email',
54
avatar: '@image(100x100)'
55
});
56
```
57
58
**Function-based Responses:**
59
60
```javascript
61
// Dynamic response based on request
62
Mock.mock('/api/search', 'get', function(options) {
63
// Access request details
64
console.log(options.url); // Request URL
65
console.log(options.type); // Request method
66
console.log(options.body); // Request body
67
68
// Return dynamic response
69
return {
70
query: options.url.split('q=')[1],
71
'results|1-20': [{
72
id: '@guid',
73
title: '@title',
74
content: '@paragraph'
75
}]
76
};
77
});
78
79
// Simulate different response statuses
80
Mock.mock('/api/login', 'post', function(options) {
81
const body = JSON.parse(options.body);
82
83
if (body.username === 'admin' && body.password === 'password') {
84
return {
85
success: true,
86
token: '@guid',
87
user: {
88
id: 1,
89
username: 'admin',
90
role: 'administrator'
91
}
92
};
93
} else {
94
return {
95
success: false,
96
message: 'Invalid credentials'
97
};
98
}
99
});
100
```
101
102
### Mock Configuration
103
104
Configure XMLHttpRequest mock behavior globally.
105
106
```javascript { .api }
107
/**
108
* Configure XMLHttpRequest mock behavior
109
* @param settings - Configuration options
110
*/
111
Mock.setup(settings: {
112
timeout?: string | number;
113
}): void;
114
```
115
116
**Configuration Examples:**
117
118
```javascript
119
// Set global timeout for mocked requests
120
Mock.setup({
121
timeout: '200-600' // Random delay between 200-600ms
122
});
123
124
// Fixed timeout
125
Mock.setup({
126
timeout: 400 // 400ms delay
127
});
128
```
129
130
### Request Options Object
131
132
When using function-based response templates, the options object contains request details.
133
134
```javascript { .api }
135
interface RequestOptions {
136
url: string; // Request URL
137
type: string; // HTTP method (GET, POST, etc.)
138
body: string; // Request body (for POST/PUT)
139
async: boolean; // Async flag
140
timeout: number; // Request timeout
141
headers: object; // Request headers
142
xhr: XMLHttpRequest; // Original XHR object
143
}
144
```
145
146
### Response Patterns
147
148
Common patterns for mocking different types of API responses.
149
150
**REST API Patterns:**
151
152
```javascript
153
// List resources
154
Mock.mock('/api/posts', 'get', {
155
'data|10-20': [{
156
'id|+1': 1,
157
title: '@title(3, 8)',
158
content: '@paragraph(2, 5)',
159
author: '@name',
160
'tags|1-3': ['javascript', 'web', 'frontend', 'backend'],
161
publishedAt: '@datetime',
162
'likes|0-100': 1
163
}],
164
total: '@natural(50, 200)',
165
page: 1,
166
pageSize: 20
167
});
168
169
// Get single resource
170
Mock.mock(/\/api\/posts\/\d+/, 'get', {
171
id: '@natural(1, 1000)',
172
title: '@title(5, 10)',
173
content: '@paragraph(5, 15)',
174
author: {
175
id: '@natural(1, 100)',
176
name: '@name',
177
avatar: '@image(50x50)'
178
},
179
'tags|2-5': ['javascript', 'nodejs', 'react', 'vue', 'angular'],
180
publishedAt: '@datetime',
181
updatedAt: '@datetime',
182
'likes|10-500': 1,
183
'comments|0-50': [{
184
id: '@natural(1, 10000)',
185
content: '@sentence(5, 20)',
186
author: '@name',
187
createdAt: '@datetime'
188
}]
189
});
190
191
// Create resource
192
Mock.mock('/api/posts', 'post', {
193
success: true,
194
message: 'Post created successfully',
195
data: {
196
id: '@inc',
197
title: '@title',
198
slug: '@string(lower, 10, 20)',
199
createdAt: '@now'
200
}
201
});
202
203
// Update resource
204
Mock.mock(/\/api\/posts\/\d+/, 'put', {
205
success: true,
206
message: 'Post updated successfully',
207
updatedAt: '@now'
208
});
209
210
// Delete resource
211
Mock.mock(/\/api\/posts\/\d+/, 'delete', {
212
success: true,
213
message: 'Post deleted successfully'
214
});
215
```
216
217
**Error Response Patterns:**
218
219
```javascript
220
// 404 Not Found
221
Mock.mock('/api/not-found', 'get', {
222
error: true,
223
code: 404,
224
message: 'Resource not found'
225
});
226
227
// Validation errors
228
Mock.mock('/api/users', 'post', function(options) {
229
return {
230
success: false,
231
code: 400,
232
message: 'Validation failed',
233
errors: {
234
email: ['Email is required', 'Email format is invalid'],
235
password: ['Password must be at least 8 characters']
236
}
237
};
238
});
239
240
// Server error simulation
241
Mock.mock('/api/server-error', 'get', {
242
error: true,
243
code: 500,
244
message: 'Internal server error'
245
});
246
```
247
248
### Integration Examples
249
250
Examples of using Mock.js with popular Ajax libraries.
251
252
**jQuery Integration:**
253
254
```javascript
255
// Setup mocks
256
Mock.mock('/api/users', 'get', {
257
'users|5': [{ id: '@inc', name: '@name' }]
258
});
259
260
// Use with jQuery
261
$.get('/api/users')
262
.done(function(data) {
263
console.log('Users:', data.users);
264
});
265
```
266
267
**Axios Integration:**
268
269
```javascript
270
// Setup mocks
271
Mock.mock('/api/posts', 'post', {
272
success: true,
273
id: '@inc'
274
});
275
276
// Use with Axios
277
axios.post('/api/posts', { title: 'New Post' })
278
.then(response => {
279
console.log('Created:', response.data);
280
});
281
```
282
283
**Fetch API Integration:**
284
285
```javascript
286
// Setup mocks
287
Mock.mock('/api/data', 'get', {
288
'items|3-8': [{ id: '@guid', value: '@natural(1, 100)' }]
289
});
290
291
// Use with fetch
292
fetch('/api/data')
293
.then(response => response.json())
294
.then(data => {
295
console.log('Data:', data.items);
296
});
297
```
298
299
### Mock Registry
300
301
Internal storage of active mocks (available for inspection).
302
303
```javascript { .api }
304
/**
305
* Internal registry of active mocks
306
* Structure: { 'url+method': { rurl, rtype, template } }
307
*/
308
Mock._mocked: { [key: string]: MockRule };
309
310
interface MockRule {
311
rurl: string | RegExp; // URL pattern
312
rtype: string; // HTTP method
313
template: any | Function; // Response template
314
}
315
```
316
317
**Registry Inspection:**
318
319
```javascript
320
// View active mocks
321
console.log(Mock._mocked);
322
323
// Check specific mock
324
const usersMock = Mock._mocked['/api/users'];
325
if (usersMock) {
326
console.log('Users API is mocked');
327
}
328
```