Fake XHR and server for testing JavaScript applications
npx @tessl/cli install tessl/npm-nise@6.1.00
# nise (偽)
1
2
nise provides comprehensive fake XMLHttpRequest (XHR) and server functionality for testing JavaScript applications. It enables developers to intercept, mock, and simulate HTTP requests and responses without making actual network calls, which is essential for unit testing, integration testing, and development environments. As part of the SinonJS ecosystem, nise is designed for maximum compatibility with testing frameworks and provides fine-grained control over network behavior.
3
4
## Package Information
5
6
- **Package Name**: nise
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install nise`
10
11
## Core Imports
12
13
```javascript
14
const { fakeServer, fakeServerWithClock, fakeXhr } = require("nise");
15
```
16
17
For ES modules (bundled version):
18
19
```javascript
20
import nise from "nise";
21
const { fakeServer, fakeServerWithClock, fakeXhr } = nise;
22
```
23
24
## Basic Usage
25
26
```javascript
27
const nise = require("nise");
28
29
// Create a fake server
30
const server = nise.fakeServer.create();
31
32
// Set up a response
33
server.respondWith("GET", "/api/users", [
34
200,
35
{ "Content-Type": "application/json" },
36
JSON.stringify([{ id: 1, name: "John" }])
37
]);
38
39
// Enable auto-response
40
server.autoRespond = true;
41
42
// Make a request (in your application code)
43
// This will be intercepted by the fake server
44
45
// Clean up
46
server.restore();
47
```
48
49
## Architecture
50
51
nise is built around three core components:
52
53
- **Fake Server**: High-level HTTP request/response mocking with pattern matching and automatic response handling
54
- **Fake Server with Clock**: Enhanced fake server integrated with fake timers for time-based testing scenarios
55
- **Fake XHR**: Low-level XMLHttpRequest replacement providing complete control over request/response lifecycle
56
57
The library supports both Node.js and browser environments, with feature detection for platform-specific capabilities like timeout handling, CORS support, and different response types (ArrayBuffer, Blob, JSON, XML).
58
59
## Capabilities
60
61
### HTTP Server Mocking
62
63
High-level interface for intercepting and responding to HTTP requests with pattern matching, automatic responses, and request history tracking.
64
65
```javascript { .api }
66
const fakeServer = {
67
/**
68
* Create a new fake server instance
69
* @param {Object} [config] - Optional configuration object
70
* @returns {Object} FakeServer instance
71
*/
72
create: function(config) {}
73
};
74
75
// FakeServer instance methods
76
const server = fakeServer.create();
77
78
/**
79
* Configure response for matching requests
80
* @param {string} method - HTTP method
81
* @param {string|RegExp|Function} url - URL pattern
82
* @param {string|Array|Function} body - Response body
83
*/
84
server.respondWith = function(method, url, body) {};
85
86
/**
87
* Process all pending requests
88
*/
89
server.respond = function() {};
90
91
/**
92
* Process all requests immediately
93
*/
94
server.respondAll = function() {};
95
96
/**
97
* Restore original XMLHttpRequest
98
*/
99
server.restore = function() {};
100
101
/**
102
* Reset server state
103
*/
104
server.reset = function() {};
105
106
/**
107
* Clear configured responses
108
*/
109
server.resetBehavior = function() {};
110
111
/**
112
* Clear request history
113
*/
114
server.resetHistory = function() {};
115
116
/**
117
* Get request by index
118
* @param {number} index - Zero-based request index
119
* @returns {XMLHttpRequest|null} Request object or null
120
*/
121
server.getRequest = function(index) {};
122
```
123
124
[HTTP Server Mocking](./fake-server.md)
125
126
### Timer-Integrated Server Mocking
127
128
Enhanced fake server that integrates with fake timers for testing time-dependent scenarios like request timeouts and delayed responses.
129
130
```javascript { .api }
131
const fakeServerWithClock = {
132
/**
133
* Create a fake server with integrated timer support
134
* @param {Object} [config] - Optional configuration object
135
* @returns {Object} FakeServerWithClock instance (includes all FakeServer methods)
136
*/
137
create: function(config) {}
138
};
139
```
140
141
[Timer-Integrated Server Mocking](./fake-server-with-clock.md)
142
143
### XMLHttpRequest Mocking
144
145
Low-level XMLHttpRequest replacement providing complete control over the request/response lifecycle, response types, and progress events.
146
147
```javascript { .api }
148
const fakeXhr = {
149
/**
150
* Replace global XMLHttpRequest with fake implementation
151
* @returns {Function} FakeXMLHttpRequest constructor
152
*/
153
useFakeXMLHttpRequest: function() {},
154
155
/**
156
* Create fake XMLHttpRequest for specific global scope
157
* @param {Object} globalScope - Global object (window/global)
158
* @returns {Object} Object with xhr utilities and FakeXMLHttpRequest
159
*/
160
fakeXMLHttpRequestFor: function(globalScope) {},
161
162
/**
163
* FakeXMLHttpRequest constructor
164
* @param {Object} [config] - Optional configuration
165
* @constructor
166
*/
167
FakeXMLHttpRequest: function(config) {}
168
};
169
170
// FakeXMLHttpRequest instance methods
171
const xhr = new fakeXhr.FakeXMLHttpRequest();
172
173
/**
174
* Initialize a request
175
* @param {string} method - HTTP method
176
* @param {string} url - Request URL
177
* @param {boolean} [async=true] - Async flag
178
* @param {string} [username] - Username for auth
179
* @param {string} [password] - Password for auth
180
*/
181
xhr.open = function(method, url, async, username, password) {};
182
183
/**
184
* Send the request
185
* @param {string|FormData|ArrayBuffer} [data] - Request body data
186
*/
187
xhr.send = function(data) {};
188
189
/**
190
* Set complete response (status, headers, and body)
191
* @param {number} status - HTTP status code
192
* @param {Object} headers - Response headers
193
* @param {string|ArrayBuffer} body - Response body
194
*/
195
xhr.respond = function(status, headers, body) {};
196
```
197
198
[XMLHttpRequest Mocking](./fake-xhr.md)
199
200
## Configuration Objects
201
202
```javascript { .api }
203
/**
204
* Server configuration object
205
* @typedef {Object} ServerConfig
206
* @property {boolean} [autoRespond] - Automatically respond to requests after a delay
207
* @property {number} [autoRespondAfter] - Delay in milliseconds for auto-response
208
* @property {boolean} [respondImmediately] - Respond to requests immediately when received
209
* @property {boolean} [fakeHTTPMethods] - Enable HTTP method override via _method parameter
210
* @property {Function} [logger] - Custom logging function
211
* @property {boolean} [unsafeHeadersEnabled] - Allow setting unsafe headers
212
*/
213
214
/**
215
* FakeXMLHttpRequest configuration object
216
* @typedef {Object} FakeXHRConfig
217
* @property {Function} [logger] - Custom logging function
218
* @property {boolean} [useImmediateExceptions] - Throw errors immediately vs on next tick
219
* @property {Function} [setTimeout] - Custom setTimeout function
220
*/
221
222
/**
223
* Response configuration object
224
* @typedef {Object} RequestResponse
225
* @property {string} [method] - HTTP method to match
226
* @property {string|RegExp|Function} [url] - URL pattern to match
227
* @property {string|Array|Function} response - Response data (status, headers, body)
228
*/
229
```