0
# Mock Controller
1
2
The Mock Controller is the central component for managing XMLHttpRequest mocks. It provides methods to set up and tear down mocks, register request handlers, and control the mock lifecycle.
3
4
## Capabilities
5
6
### Setup and Teardown
7
8
Controls the mock lifecycle by replacing and restoring the global XMLHttpRequest object.
9
10
```typescript { .api }
11
/**
12
* Replace the global XMLHttpRequest object with the mock implementation
13
* @returns XHRMock instance for chaining
14
*/
15
setup(): XHRMock;
16
17
/**
18
* Restore the global XMLHttpRequest object to its original state
19
* @returns XHRMock instance for chaining
20
*/
21
teardown(): XHRMock;
22
23
/**
24
* Clear all registered request handlers
25
* @returns XHRMock instance for chaining
26
*/
27
reset(): XHRMock;
28
```
29
30
**Usage Example:**
31
32
```typescript
33
import mock from 'xhr-mock';
34
35
// Set up mocks before your tests
36
mock.setup();
37
38
// Your test code here...
39
40
// Clean up mocks after your tests
41
mock.teardown();
42
```
43
44
### Error Handling
45
46
Register a callback to handle errors that occur in mock handlers.
47
48
```typescript { .api }
49
/**
50
* Set error callback for handler errors
51
* @param callback - Function to handle errors from mock handlers
52
* @returns XHRMock instance for chaining
53
*/
54
error(callback: (event: ErrorCallbackEvent) => void): XHRMock;
55
56
interface ErrorCallbackEvent {
57
req: MockRequest;
58
err: Error;
59
}
60
```
61
62
**Usage Example:**
63
64
```typescript
65
mock.error((event) => {
66
console.error('Mock handler error:', event.err);
67
console.log('Request that caused error:', event.req.method(), event.req.url());
68
});
69
```
70
71
### Request Handler Registration
72
73
Register mock handlers for specific requests or all requests.
74
75
```typescript { .api }
76
/**
77
* Register a mock function for all requests
78
* @param fn - Function that handles all requests
79
* @returns XHRMock instance for chaining
80
*/
81
use(fn: MockFunction): XHRMock;
82
83
/**
84
* Register a mock for specific HTTP method and URL pattern
85
* @param method - HTTP method (GET, POST, PUT, PATCH, DELETE)
86
* @param url - URL string or RegExp pattern to match
87
* @param mock - Mock object or function to handle the request
88
* @returns XHRMock instance for chaining
89
*/
90
use(method: string, url: string | RegExp, mock: Mock): XHRMock;
91
```
92
93
**Usage Examples:**
94
95
```typescript
96
// Handle all requests with a function
97
mock.use((req, res) => {
98
if (req.url().path === '/api/status') {
99
return res.status(200).body('OK');
100
}
101
// Return undefined to pass to next handler
102
});
103
104
// Handle specific method and URL
105
mock.use('GET', '/api/users', {
106
status: 200,
107
body: JSON.stringify([{ id: 1, name: 'John' }])
108
});
109
110
// Using RegExp for URL matching
111
mock.use('POST', /\/api\/users\/\d+/, (req, res) => {
112
return res.status(204);
113
});
114
```
115
116
### HTTP Method Shortcuts
117
118
Convenient methods for registering handlers for specific HTTP methods.
119
120
```typescript { .api }
121
/**
122
* Register a mock for GET requests to specific URL
123
* @param url - URL string or RegExp pattern to match
124
* @param mock - Mock object or function to handle the request
125
* @returns XHRMock instance for chaining
126
*/
127
get(url: string | RegExp, mock: Mock): XHRMock;
128
129
/**
130
* Register a mock for POST requests to specific URL
131
* @param url - URL string or RegExp pattern to match
132
* @param mock - Mock object or function to handle the request
133
* @returns XHRMock instance for chaining
134
*/
135
post(url: string | RegExp, mock: Mock): XHRMock;
136
137
/**
138
* Register a mock for PUT requests to specific URL
139
* @param url - URL string or RegExp pattern to match
140
* @param mock - Mock object or function to handle the request
141
* @returns XHRMock instance for chaining
142
*/
143
put(url: string | RegExp, mock: Mock): XHRMock;
144
145
/**
146
* Register a mock for PATCH requests to specific URL
147
* @param url - URL string or RegExp pattern to match
148
* @param mock - Mock object or function to handle the request
149
* @returns XHRMock instance for chaining
150
*/
151
patch(url: string | RegExp, mock: Mock): XHRMock;
152
153
/**
154
* Register a mock for DELETE requests to specific URL
155
* @param url - URL string or RegExp pattern to match
156
* @param mock - Mock object or function to handle the request
157
* @returns XHRMock instance for chaining
158
*/
159
delete(url: string | RegExp, mock: Mock): XHRMock;
160
```
161
162
**Usage Examples:**
163
164
```typescript
165
// Simple object responses
166
mock.get('/api/users', {
167
status: 200,
168
headers: { 'Content-Type': 'application/json' },
169
body: JSON.stringify([{ id: 1, name: 'John' }])
170
});
171
172
mock.post('/api/users', {
173
status: 201,
174
body: JSON.stringify({ id: 2, name: 'Jane' })
175
});
176
177
// Function responses for dynamic behavior
178
mock.put('/api/users/:id', (req, res) => {
179
const userData = JSON.parse(req.body());
180
return res
181
.status(200)
182
.header('Content-Type', 'application/json')
183
.body(JSON.stringify({ ...userData, updated: true }));
184
});
185
186
// Using RegExp for complex URL patterns
187
mock.delete(/\/api\/users\/\d+/, (req, res) => {
188
return res.status(204);
189
});
190
```
191
192
### Deprecated Methods
193
194
**Note**: The following methods are deprecated and should be replaced with `use()`:
195
196
```typescript { .api }
197
/**
198
* @deprecated Use use() instead
199
*/
200
mock(fn: MockFunction): XHRMock;
201
mock(method: string, url: string | RegExp, mock: Mock): XHRMock;
202
```
203
204
## Types
205
206
```typescript { .api }
207
type MockFunction = (
208
request: MockRequest,
209
response: MockResponse
210
) => undefined | MockResponse | Promise<undefined | MockResponse>;
211
212
interface MockObject {
213
status?: number;
214
reason?: string;
215
headers?: MockHeaders;
216
body?: any;
217
}
218
219
type Mock = MockObject | MockFunction;
220
221
type MockHeaders = {[name: string]: string};
222
```