Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
fakeXhr
✓ import { fakeXhr } from 'nise';
✗ const fakeXhr = require('nise').fakeXhr;
While CommonJS `require` is supported via `const { fakeXhr } = require('nise');`, modern applications and build tools prefer ES module imports for better tree-shaking and consistency. Nise's `package.json` includes both `main` (CJS) and `module` (ESM) entry points.
fakeServer
✓ import { fakeServer } from 'nise';
✗ const fakeServer = require('nise').fakeServer;
The `fakeServer` constructor is a named export. Ensure you import it by name. Direct use of `require('nise')` in a CommonJS context would require accessing the `fakeServer` property from the returned module object.
FakeXMLHttpRequest
✓ import { FakeXMLHttpRequest } from 'nise';
✗ import { XMLHttpRequest } from 'nise';
This is the constructor for individual fake XHR objects, exposed for advanced usage or custom implementations. It is distinct from the `fakeXhr` utility which replaces the global native `XMLHttpRequest`.
This example demonstrates how to use `fakeXhr` to intercept XMLHttpRequest calls globally and `fakeServer` to define specific responses for different HTTP requests. It shows both setup and teardown for proper test isolation and preventing side effects.
import { fakeXhr, fakeServer } from 'nise';
// 1. Using fakeXhr to replace the global XMLHttpRequest
let xhr: typeof XMLHttpRequest | undefined;
let capturedRequests: XMLHttpRequest[] = [];
function setupFakeXhr() {
xhr = fakeXhr.useFakeXMLHttpRequest();
xhr.onCreate = function (req) {
capturedRequests.push(req);
};
console.log('Fake XHR initialized.');
}
function teardownFakeXhr() {
if (xhr) {
xhr.restore();
capturedRequests = [];
console.log('Fake XHR restored.');
}
}
// 2. Using fakeServer for more complete control and automatic global replacement
let server: InstanceType<typeof fakeServer> | undefined;
function setupFakeServer() {
server = fakeServer.create();
// Configure a response for a GET request to /users
server.respondWith('GET', '/users', [
200, // HTTP Status Code
{ 'Content-Type': 'application/json' }, // Headers
JSON.stringify([{ id: 1, name: 'Alice' }]) // Response Body
]);
// Configure a response for a POST request to /users
server.respondWith('POST', '/users', [
201,
{ 'Content-Type': 'application/json' },
JSON.stringify({ id: 2, name: 'Bob' })
]);
console.log('Fake Server initialized.');
}
function teardownFakeServer() {
if (server) {
server.restore();
console.log('Fake Server restored.');
}
}
// --- Demonstration with fakeXhr ---
setupFakeXhr();
const req1 = new XMLHttpRequest();
req1.open('GET', '/data');
req1.send();
console.log(`Fake XHR captured request method: ${capturedRequests[0].method}, URL: ${capturedRequests[0].url}`);
teardownFakeXhr();
console.log('\n--- Demonstration with fakeServer ---\n');
// --- Demonstration with fakeServer ---
setupFakeServer();
// Make a GET request
const req2 = new XMLHttpRequest();
req2.open('GET', '/users');
req2.onload = function() {
console.log(`Fake Server GET response: ${req2.status} - ${req2.responseText}`);
};
req2.send();
server!.respond(); // Manually trigger server response
// Make a POST request
const req3 = new XMLHttpRequest();
req3.open('POST', '/users');
req3.onload = function() {
console.log(`Fake Server POST response: ${req3.status} - ${req3.responseText}`);
};
req3.setRequestHeader('Content-Type', 'application/json');
req3.send(JSON.stringify({ name: 'Bob' }));
server!.respond(); // Manually trigger server response
teardownFakeServer();
Errors
Common errors & fixes
TypeError: XMLHttpRequest is not a constructor
This error occurs when `new XMLHttpRequest()` is called in a Node.js environment that lacks a global `XMLHttpRequest` polyfill, or before `nise` has been initialized to provide its fake implementation.
fixEnsure that a browser emulation layer (e.g., `jsdom`) is set up in your Node.js test environment, or that `fakeXhr.useFakeXMLHttpRequest()` or `fakeServer.create()` has been called to mock the global `XMLHttpRequest` object.
Error: XHR has already been faked. Call `restore()` on the current fake XHR object before faking again.
You are attempting to call `fakeXhr.useFakeXMLHttpRequest()` or `fakeServer.create()` multiple times within the same context (e.g., without proper cleanup between tests) without first calling `restore()` on the previously active fake XHR instance.
fixModify your test setup to ensure that `restore()` is invoked on the previously activated `fakeXhr` or `fakeServer` instance (e.g., in an `afterEach` or `afterAll` hook) before any new fakes are created.
ReferenceError: require is not defined
This error typically occurs when an ES module using `import ... from 'nise'` is executed in a Node.js environment configured exclusively for CommonJS modules, or vice-versa, without appropriate transpilation or configuration.
fixFor ES Modules, ensure your `package.json` contains `"type": "module"` and use `import` statements. For CommonJS, use `require` statements. Verify your Node.js environment and file extensions (`.js`, `.mjs`, `.cjs`) align with the module system you intend to use.
Audit
Dependencies
@sinonjs/commonsrequiredProvides shared utility functions and common helpers used across the Sinon.JS ecosystem, including Nise.
@sinonjs/fake-timersrequiredOffers faked global timer functions (like `setTimeout`, `setInterval`) which are often needed to control time in tests, especially when simulating network delays with `fakeServer` or `fakeXhr`.
@sinonjs/text-encodingrequiredUsed for robust handling of text encoding and decoding within XHR responses, ensuring compatibility and correctness.
just-extendrequiredA small, focused utility library for recursively extending JavaScript objects, used internally by Nise.
path-to-regexprequiredEnables powerful and flexible URL path matching capabilities, critical for routing and responding to specific requests within the `fakeServer`.