{"id":14374,"library":"xhr-mocklet","title":"XHR Mocklet","description":"`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.","status":"active","version":"1.2.3","language":"javascript","source_language":"en","source_url":"git://github.com/marvinhagemeister/xhr-mocklet","tags":["javascript","mock","xhr","test","fake","request","ajax","browser","xmlhttprequest","typescript"],"install":[{"cmd":"npm install xhr-mocklet","lang":"bash","label":"npm"},{"cmd":"yarn add xhr-mocklet","lang":"bash","label":"yarn"},{"cmd":"pnpm add xhr-mocklet","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"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.","wrong":"import { mock } from 'xhr-mocklet';","symbol":"mock","correct":"import mock from 'xhr-mocklet';"},{"note":"Typical CommonJS usage involves requiring the default export, which is an object containing all the library's main functions.","wrong":"const { mock } = require('xhr-mocklet');","symbol":"mock","correct":"const mock = require('xhr-mocklet');"},{"note":"These types are useful for accurately typing the `req` and `res` parameters within mock handler functions, enhancing type safety in TypeScript projects.","symbol":"MockRequest, MockResponse","correct":"import type { MockRequest, MockResponse } from 'xhr-mocklet';"}],"quickstart":{"code":"import mock from 'xhr-mocklet';\n\n// 1. Replace the real XHR object with the mock XHR object\nmock.setup();\n\n// 2. Define a mock response for a specific POST request\nmock.post('http://localhost/api/user', (req, res) => {\n  console.log('Mocked POST request received for:', req.url());\n  console.log('Request body:', req.body());\n  return res\n    .status(201)\n    .header('Content-Type', 'application/json')\n    .body(JSON.stringify({\n      lastName: 'John',\n      firstName: 'Smith'\n    }));\n});\n\n// 3. Simulate making an XMLHttpRequest\nconst xhr = new XMLHttpRequest();\nxhr.open('POST', 'http://localhost/api/user');\nxhr.setRequestHeader('Content-Type', 'application/json');\n\nxhr.onload = function() {\n  if (xhr.status === 201) {\n    console.log('Response status:', xhr.status);\n    console.log('Response body:', xhr.responseText);\n  } else {\n    console.error('Request failed with status:', xhr.status);\n  }\n  // 4. Restore the original XHR object after the test is done\n  mock.teardown();\n};\n\nxhr.onerror = function() {\n  console.error('XHR error occurred');\n  mock.teardown();\n};\n\nxhr.send(JSON.stringify({ firstName: 'Test', lastName: 'User' }));\n\nconsole.log('XHR Mocklet quickstart initiated. Check console for output after the simulated request completes.');\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Always ensure `mock.teardown()` is called in `afterEach` or `afterAll` hooks in your testing framework to prevent state leakage and ensure test isolation.","message":"Using `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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For network errors, a mock handler should `return null;`. For timeouts, a mock handler should `return res.timeout(true);`.","message":"Simulating 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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)`.","message":"Prior 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.","severity":"gotcha","affected_versions":">=1.1.0"}],"env_vars":null,"search_vec":"'1.2.3':30 'addit':47 'address':41 'ajax':121 'allow':50 'also':101 'api':93 'browser':19,122 'bug':42 'clear':92 'comprehens':103 'control':72 'current':27 'custom':54 'declar':105 'defin':53 'design':10 'develop':51,110 'differenti':80 'direct':85 'ensur':107 'environ':22 'error':64 'experi':111 'fake':119 'featur':46 'file':106 'fine':70 'fine-grain':69 'fix':43 'focus':86 'grain':71 'handl':99 'http':58 'indic':36 'interact':75 'intercept':12 'javascript':115 'key':79 'librari':49 'lightweight':8 'method':59 'minor':45 'mock':14,89,116 'mocklet':2,5 'need':35 'network':63,74 'node.js':21 'object':16 'offer':90 'patch':39 'primarili':23 'provid':68,102 'receiv':32 'recent':38 'releas':40 'request':98,120 'respons':55 'robust':109 'setup':95 'simplic':83 'simul':62 'specif':57 'teardown':96 'test':26,77,118 'timeout':67 'trigger':66 'typescript':104,113,124 'unit':25 'updat':33 'url':61 'user':114 'util':9 'version':29 'xhr':1,4,117 'xhr-mocklet':3 'xmlhttprequest':15,88,123","created_at":"2026-04-20T01:59:22.846187+00:00","updated_at":"2026-04-20T01:59:22.846187+00:00","problems":[{"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.","cause":"The `xhr-mocklet` module was not correctly imported or required, meaning the `mock` object is `undefined` or not the expected object.","error":"TypeError: Cannot read properties of undefined (reading 'setup')"},{"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.","cause":"The actual `XMLHttpRequest` request URL, method, or other parameters do not precisely match any defined mock handler, or `mock.teardown()` was called prematurely.","error":"Network request failed"},{"fix":"Implement `mock.teardown()` in your test runner's `afterEach` or `afterAll` hook to guarantee a clean state between tests or test files.","cause":"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.","error":"Tests intermittently pass/fail or show unexpected network activity."}],"ecosystem":"npm","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/marvinhagemeister/xhr-mocklet","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/xhr-mocklet","openapi_spec":null,"status_page":null,"smithery":null,"categories":["testing","http-networking"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}