Nise Fake XHR and Server

6.1.5 · active · verified Sun Apr 19

Nise (偽) is a JavaScript library designed for faking XMLHttpRequest (XHR) and creating a fake server environment, primarily used in testing scenarios. It allows developers to intercept and control network requests made by their application without actually performing real HTTP calls. Extracted from the larger Sinon.JS library, Nise offers a lightweight alternative for users who only require XHR and server mocking functionalities, avoiding the overhead of the full Sinon.JS suite. The current stable version is 6.1.5, which was recently published as a patch. The project maintains an active, albeit slower, release cadence for minor and patch versions, driven by community needs and bug fixes. Its key differentiator is its focused scope and tight integration within the Sinon.JS testing ecosystem, providing a reliable and robust solution for simulating server interactions during unit and integration tests.

Common errors

Warnings

Install

Imports

Quickstart

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();

view raw JSON →