`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-mockletVerified import paths — ran on the pinned version, not inferred.
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.
Always ensure `mock.teardown()` is called in `afterEach` or `afterAll` hooks in your testing framework to prevent state leakage and ensure test isolation.
For network errors, a mock handler should `return null;`. For timeouts, a mock handler should `return res.timeout(true);`.
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)`.
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.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.Implement `mock.teardown()` in your test runner's `afterEach` or `afterAll` hook to guarantee a clean state between tests or test files.
No dependency data recorded yet.