{"id":14727,"library":"nise","title":"Nise Fake XHR and Server","description":"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.","status":"active","version":"6.1.5","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/sinonjs/nise","tags":["javascript","test","testing","fake","mock","xhr","server"],"install":[{"cmd":"npm install nise","lang":"bash","label":"npm"},{"cmd":"yarn add nise","lang":"bash","label":"yarn"},{"cmd":"pnpm add nise","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Provides shared utility functions and common helpers used across the Sinon.JS ecosystem, including Nise.","package":"@sinonjs/commons"},{"reason":"Offers 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`.","package":"@sinonjs/fake-timers"},{"reason":"Used for robust handling of text encoding and decoding within XHR responses, ensuring compatibility and correctness.","package":"@sinonjs/text-encoding"},{"reason":"A small, focused utility library for recursively extending JavaScript objects, used internally by Nise.","package":"just-extend"},{"reason":"Enables powerful and flexible URL path matching capabilities, critical for routing and responding to specific requests within the `fakeServer`.","package":"path-to-regexp"}],"imports":[{"note":"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.","wrong":"const fakeXhr = require('nise').fakeXhr;","symbol":"fakeXhr","correct":"import { fakeXhr } from 'nise';"},{"note":"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.","wrong":"const fakeServer = require('nise').fakeServer;","symbol":"fakeServer","correct":"import { fakeServer } from 'nise';"},{"note":"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`.","wrong":"import { XMLHttpRequest } from 'nise';","symbol":"FakeXMLHttpRequest","correct":"import { FakeXMLHttpRequest } from 'nise';"}],"quickstart":{"code":"import { fakeXhr, fakeServer } from 'nise';\n\n// 1. Using fakeXhr to replace the global XMLHttpRequest\nlet xhr: typeof XMLHttpRequest | undefined;\nlet capturedRequests: XMLHttpRequest[] = [];\n\nfunction setupFakeXhr() {\n  xhr = fakeXhr.useFakeXMLHttpRequest();\n  xhr.onCreate = function (req) {\n    capturedRequests.push(req);\n  };\n  console.log('Fake XHR initialized.');\n}\n\nfunction teardownFakeXhr() {\n  if (xhr) {\n    xhr.restore();\n    capturedRequests = [];\n    console.log('Fake XHR restored.');\n  }\n}\n\n// 2. Using fakeServer for more complete control and automatic global replacement\nlet server: InstanceType<typeof fakeServer> | undefined;\n\nfunction setupFakeServer() {\n  server = fakeServer.create();\n  // Configure a response for a GET request to /users\n  server.respondWith('GET', '/users', [\n    200, // HTTP Status Code\n    { 'Content-Type': 'application/json' }, // Headers\n    JSON.stringify([{ id: 1, name: 'Alice' }]) // Response Body\n  ]);\n  // Configure a response for a POST request to /users\n  server.respondWith('POST', '/users', [\n    201,\n    { 'Content-Type': 'application/json' },\n    JSON.stringify({ id: 2, name: 'Bob' })\n  ]);\n  console.log('Fake Server initialized.');\n}\n\nfunction teardownFakeServer() {\n  if (server) {\n    server.restore();\n    console.log('Fake Server restored.');\n  }\n}\n\n// --- Demonstration with fakeXhr ---\nsetupFakeXhr();\nconst req1 = new XMLHttpRequest();\nreq1.open('GET', '/data');\nreq1.send();\nconsole.log(`Fake XHR captured request method: ${capturedRequests[0].method}, URL: ${capturedRequests[0].url}`);\nteardownFakeXhr();\n\nconsole.log('\\n--- Demonstration with fakeServer ---\\n');\n\n// --- Demonstration with fakeServer ---\nsetupFakeServer();\n// Make a GET request\nconst req2 = new XMLHttpRequest();\nreq2.open('GET', '/users');\nreq2.onload = function() {\n  console.log(`Fake Server GET response: ${req2.status} - ${req2.responseText}`);\n};\nreq2.send();\nserver!.respond(); // Manually trigger server response\n\n// Make a POST request\nconst req3 = new XMLHttpRequest();\nreq3.open('POST', '/users');\nreq3.onload = function() {\n  console.log(`Fake Server POST response: ${req3.status} - ${req3.responseText}`);\n};\nreq3.setRequestHeader('Content-Type', 'application/json');\nreq3.send(JSON.stringify({ name: 'Bob' }));\nserver!.respond(); // Manually trigger server response\n\nteardownFakeServer();","lang":"typescript","description":"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."},"warnings":[{"fix":"Always pair `fakeXhr.useFakeXMLHttpRequest()` with `xhr.restore()`, or `fakeServer.create()` with `server.restore()` in your test teardown (e.g., `afterEach` hook in Mocha/Jest, or `afterAll`).","message":"Faking global XHR objects via `fakeXhr.useFakeXMLHttpRequest()` or `fakeServer.create()` replaces the native XMLHttpRequest. It is crucial to call `restore()` on the returned instance after each test or test suite. Failing to do so can lead to unexpected behavior and hard-to-debug side effects in subsequent tests or other parts of your application.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure `server.respond()` is called at the appropriate time in your test to trigger responses. For scenarios where automatic responses are desired, you can set `server.autoRespond = true;` or `server.autoRespond = <delayInMillis>;` after creating the server instance.","message":"When using `fakeServer`, network requests are not automatically responded to by default. You must explicitly call `server.respond()` to process pending requests and send configured responses. This is important for controlling the flow of asynchronous operations in your tests.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For Node.js testing, configure your environment to provide a global `XMLHttpRequest` constructor using a library like `jsdom` before initializing `nise`'s fakes.","message":"Nise's fake XHR functionality is primarily designed for browser-like environments. When used in Node.js, a global `XMLHttpRequest` polyfill (such as one provided by `jsdom`) must be present for Nise to effectively replace and control it. Without this, operations might fail or not behave as expected.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure 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.","cause":"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.","error":"TypeError: XMLHttpRequest is not a constructor"},{"fix":"Modify 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.","cause":"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.","error":"Error: XHR has already been faked. Call `restore()` on the current fake XHR object before faking again."},{"fix":"For 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.","cause":"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.","error":"ReferenceError: require is not defined"}],"ecosystem":"npm"}