A comprehensive XMLHttpRequest mocking utility for testing and prototyping web applications.
npx @tessl/cli install tessl/npm-xhr-mock@2.5.00
# xhr-mock
1
2
xhr-mock is a comprehensive XMLHttpRequest mocking utility designed for testing and prototyping web applications. It enables developers to replace the global XMLHttpRequest object with a mock implementation that can simulate HTTP responses, errors, timeouts, and progress events.
3
4
## Package Information
5
6
- **Package Name**: xhr-mock
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install --save-dev xhr-mock`
10
11
## Core Imports
12
13
```typescript
14
import mock from 'xhr-mock';
15
import { MockRequest, MockResponse, proxy, once, delay, sequence } from 'xhr-mock';
16
```
17
18
For CommonJS:
19
20
```javascript
21
const mock = require('xhr-mock');
22
const { MockRequest, MockResponse, proxy, once, delay, sequence } = require('xhr-mock');
23
```
24
25
For browser without bundler:
26
27
```html
28
<script src="https://unpkg.com/xhr-mock/dist/xhr-mock.js"></script>
29
<!-- Global XHRMock variable is now available -->
30
```
31
32
## Basic Usage
33
34
```typescript
35
import mock from 'xhr-mock';
36
37
describe('API Tests', () => {
38
// Setup mock before each test
39
beforeEach(() => mock.setup());
40
41
// Teardown mock after each test
42
afterEach(() => mock.teardown());
43
44
it('should mock GET requests', async () => {
45
// Mock a GET request
46
mock.get('/api/users', {
47
status: 200,
48
headers: { 'Content-Type': 'application/json' },
49
body: JSON.stringify([{ id: 1, name: 'John' }])
50
});
51
52
// Make actual request (using any HTTP library)
53
const response = await fetch('/api/users');
54
const users = await response.json();
55
56
expect(users).toEqual([{ id: 1, name: 'John' }]);
57
});
58
59
it('should mock with custom function', async () => {
60
mock.post('/api/users', (req, res) => {
61
const userData = JSON.parse(req.body());
62
return res.status(201).body(JSON.stringify({
63
id: 123,
64
...userData
65
}));
66
});
67
68
// Test your code that makes POST requests
69
});
70
});
71
```
72
73
## Architecture
74
75
xhr-mock is built around several key components:
76
77
- **Mock Controller**: Central `XHRMock` class for setting up and managing mocks
78
- **Request/Response Objects**: `MockRequest` and `MockResponse` classes for inspecting and building HTTP interactions
79
- **Mock Patterns**: URL and HTTP method pattern matching for request routing
80
- **Utility Functions**: Helper functions for common scenarios like delays, one-time responses, and sequences
81
- **XMLHttpRequest Replacement**: Complete mock implementation that follows the XMLHttpRequest specification
82
83
## Capabilities
84
85
### Mock Controller
86
87
Core mock management functionality for setting up XMLHttpRequest mocks, registering handlers, and controlling the mock lifecycle.
88
89
```typescript { .api }
90
class XHRMock {
91
setup(): XHRMock;
92
teardown(): XHRMock;
93
reset(): XHRMock;
94
error(callback: (event: ErrorCallbackEvent) => void): XHRMock;
95
use(fn: MockFunction): XHRMock;
96
use(method: string, url: string | RegExp, mock: Mock): XHRMock;
97
get(url: string | RegExp, mock: Mock): XHRMock;
98
post(url: string | RegExp, mock: Mock): XHRMock;
99
put(url: string | RegExp, mock: Mock): XHRMock;
100
patch(url: string | RegExp, mock: Mock): XHRMock;
101
delete(url: string | RegExp, mock: Mock): XHRMock;
102
}
103
```
104
105
[Mock Controller](./mock-controller.md)
106
107
### Request and Response Objects
108
109
Classes for inspecting incoming requests and building mock responses with full control over headers, body, and status codes.
110
111
```typescript { .api }
112
class MockRequest {
113
method(): string;
114
method(method: string): MockRequest;
115
url(): MockURL;
116
url(url: string): MockRequest;
117
header(name: string): null | string;
118
header(name: string, value: string): MockRequest;
119
headers(): MockHeaders;
120
headers(headers: MockHeaders): MockRequest;
121
body(): any;
122
body(body: any): MockRequest;
123
}
124
125
class MockResponse {
126
status(): number;
127
status(status: number): MockResponse;
128
reason(): string;
129
reason(reason: string): MockResponse;
130
header(name: string): null | string;
131
header(name: string, value: string): MockResponse;
132
headers(): MockHeaders;
133
headers(headers: MockHeaders): MockResponse;
134
body(): any;
135
body(body: any): MockResponse;
136
}
137
```
138
139
[Request and Response Objects](./request-response.md)
140
141
### Utility Functions
142
143
Helper functions for advanced mocking scenarios including delays, one-time responses, response sequences, and request proxying.
144
145
```typescript { .api }
146
function once(mock: MockFunction | MockObject): MockFunction;
147
function delay(mock: MockFunction | MockObject, ms?: number): MockFunction;
148
function sequence(mocks: (MockFunction | MockObject)[]): MockFunction;
149
function proxy(req: MockRequest, res: MockResponse): Promise<MockResponse>;
150
```
151
152
[Utility Functions](./utilities.md)
153
154
## Core Types
155
156
```typescript { .api }
157
type MockHeaders = {[name: string]: string};
158
159
interface MockObject {
160
status?: number;
161
reason?: string;
162
headers?: MockHeaders;
163
body?: any;
164
}
165
166
type MockFunction = (
167
request: MockRequest,
168
response: MockResponse
169
) => undefined | MockResponse | Promise<undefined | MockResponse>;
170
171
type Mock = MockObject | MockFunction;
172
173
interface ErrorCallbackEvent {
174
req: MockRequest;
175
err: Error;
176
}
177
```