Registry / testing / xhr-mocklet

xhr-mocklet

JSON →
library1.2.3jsnpmunverified

`xhr-mocklet` is a lightweight utility designed for intercepting and mocking `XMLHttpRequest` objects in both browser and Node.js environments, primarily for unit testing. Currently at version 1.2.3, it receives updates as needed, indicated by recent patch releases addressing bug fixes and minor feature additions. The library allows developers to define custom responses for specific HTTP methods and URLs, simulate network errors, and trigger timeouts, providing fine-grained control over network interactions during tests. A key differentiator is its simplicity and direct focus on `XMLHttpRequest` mocking, offering a clear API for setup, teardown, and request handling. It also provides comprehensive TypeScript declaration files, ensuring a robust developer experience for TypeScript users.

npm install xhr-mocklet
INSTALL
IMPORT
SIG · XHR-MOCKLET
X
xhr-mocklet
testingjavascriptv1.2.3
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
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
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

mock
import mock from 'xhr-mocklet';
import { mock } from 'xhr-mocklet';
The primary API is accessed via the default export, an object containing builder methods like `setup`, `post`, and `teardown`. This is common for modules primarily exporting a single, central object.
mock
const mock = require('xhr-mocklet');
const { mock } = require('xhr-mocklet');
Typical CommonJS usage involves requiring the default export, which is an object containing all the library's main functions.
MockRequest, MockResponse
import type { MockRequest, MockResponse } from 'xhr-mocklet';
These types are useful for accurately typing the `req` and `res` parameters within mock handler functions, enhancing type safety in TypeScript projects.

This example demonstrates how to set up `xhr-mocklet`, define a mock for a POST request, simulate an XMLHttpRequest using the mocked object, and finally tear down the mock to restore the original XHR behavior.

import mock from 'xhr-mocklet'; // 1. Replace the real XHR object with the mock XHR object mock.setup(); // 2. Define a mock response for a specific POST request mock.post('http://localhost/api/user', (req, res) => { console.log('Mocked POST request received for:', req.url()); console.log('Request body:', req.body()); return res .status(201) .header('Content-Type', 'application/json') .body(JSON.stringify({ lastName: 'John', firstName: 'Smith' })); }); // 3. Simulate making an XMLHttpRequest const xhr = new XMLHttpRequest(); xhr.open('POST', 'http://localhost/api/user'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function() { if (xhr.status === 201) { console.log('Response status:', xhr.status); console.log('Response body:', xhr.responseText); } else { console.error('Request failed with status:', xhr.status); } // 4. Restore the original XHR object after the test is done mock.teardown(); }; xhr.onerror = function() { console.error('XHR error occurred'); mock.teardown(); }; xhr.send(JSON.stringify({ firstName: 'Test', lastName: 'User' })); console.log('XHR Mocklet quickstart initiated. Check console for output after the simulated request completes.');
Debug
Known issues
gotchaUsing `mock.setup()` globally modifies `window.XMLHttpRequest` (in browsers) or the global `XMLHttpRequest` constructor (in Node.js). This can lead to test isolation issues if `mock.teardown()` is not reliably called after each test or test suite, affecting subsequent tests or other parts of your application.
fix
Always ensure `mock.teardown()` is called in `afterEach` or `afterAll` hooks in your testing framework to prevent state leakage and ensure test isolation.
affects: >=1.0.0
gotchaSimulating network errors or timeouts requires specific patterns: return `null` from a handler to cause a network error, or call `res.timeout(true)` to trigger a timeout. Simply returning an empty response or a non-2xx status code will not simulate these network-level failures.
fix
For network errors, a mock handler should `return null;`. For timeouts, a mock handler should `return res.timeout(true);`.
affects: >=1.0.0
gotchaPrior to version 1.1.0, the default `status` for a mocked response was `0`. Since 1.1.0, the default `status` is `200`. If upgrading from an older version, ensure your tests explicitly set status codes where `0` was implicitly relied upon, or handle the new `200` default.
fix
Review existing mock handlers after upgrading to version 1.1.0 or newer. If a `0` status was expected by default, explicitly set `res.status(0)`.
affects: >=1.1.0
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'setup')
The `xhr-mocklet` module was not correctly imported or required, meaning the `mock` object is `undefined` or not the expected object.
fix
Ensure you are using the correct import statement for your environment: `import mock from 'xhr-mocklet';` for ESM or TypeScript, or `const mock = require('xhr-mocklet');` for CommonJS.
Network request failed
The actual `XMLHttpRequest` request URL, method, or other parameters do not precisely match any defined mock handler, or `mock.teardown()` was called prematurely.
fix
Verify that the `method` and `URL` (including query parameters if applicable) in your `xhr.open()` call exactly match a registered mock (e.g., `mock.post('/api/data', ...) `). Also, ensure `mock.teardown()` is called only after all relevant asynchronous operations have completed.
Tests intermittently pass/fail or show unexpected network activity.
Test isolation issues, where `mock.setup()` was called but `mock.teardown()` was missed in a previous test, leaving the global `XMLHttpRequest` object mocked for subsequent tests.
fix
Implement `mock.teardown()` in your test runner's `afterEach` or `afterAll` hook to guarantee a clean state between tests or test files.
Upgrade
Version history
1.2.3latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
32 hits · last 30 days
node
26
OpenAI (training)
1
Resources
xhr-mocklet — npm install xhr-mocklet · libregistry