Registry / testing / http-request-mock

http-request-mock

JSON →
library2.0.2jsnpmunverified

http-request-mock is a versatile JavaScript/TypeScript library designed for intercepting and mocking HTTP requests across various environments and client libraries. It operates at a low level, directly hooking into XMLHttpRequest, fetch, and Node.js's native http/https modules, allowing it to mock requests from popular libraries like Axios, jQuery, Superagent, Ky, Node-Fetch, and Got without specific integrations for each. The current stable version is 2.0.2. The library aims to provide a 'non-hacking' approach to mocking by offering a webpack plugin and a command-line tool, enabling separation of mock data from business logic and eliminating the need for code modifications during development or testing. Its core differentiator is this low-level, environment-agnostic interception combined with tooling for externalizing mock configurations, which distinguishes it from libraries that require proxy setups or direct code alterations.

npm install http-request-mock
INSTALL
IMPORT
SIG · HTTP-REQUEST-MOCK
H
http-request-mock
testingjavascriptv2.0.2
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 'http-request-mock'
const mock = require('http-request-mock')
The primary API surface is exposed as the default export, commonly aliased as `mock`. This allows access to setup, teardown, and request mocking methods.
MockOptions
import type { MockOptions } from 'http-request-mock'
import { MockOptions } from 'http-request-mock'
Import TypeScript types using `import type` to clearly distinguish them from runtime values and prevent accidental bundling in environments that don't strip types automatically.
MockItem
import type { MockItem } from 'http-request-mock'
import { MockItem } from 'http-request-mock'
This type defines the structure of an individual mock configuration. Use `import type` for type-only imports.

Sets up `http-request-mock` to intercept and respond to GET and POST requests for a `/api/users` endpoint, showcasing dynamic responses, status codes, and network delays. It then simulates client-side `fetch` calls to trigger these mocked behaviors.

import mock from 'http-request-mock'; // Initialize the mocking library to intercept requests mock.setup(); // Mock a GET request to /api/users with a static JSON response mock.get('/api/users', (req) => { console.log('Intercepted GET /api/users request:', req.url); return { status: 200, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify([ { id: 1, name: 'Alice', email: 'alice@example.com' }, { id: 2, name: 'Bob', email: 'bob@example.com' } ]) }; }, { delay: 500 }); // Simulate network latency with a 500ms delay // Mock a POST request to /api/users with a dynamic response based on request body mock.post('/api/users', (req) => { const newUser = JSON.parse(req.body); console.log('Intercepted POST /api/users request with data:', newUser); return { status: 201, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: Math.floor(Math.random() * 1000) + 3, ...newUser }) }; }); // Simulate client-side requests using fetch async function fetchAndLogUsers() { console.log('\nAttempting to fetch users...'); try { const response = await fetch('/api/users'); const data = await response.json(); console.log('Fetched users (mocked):', data); } catch (error) { console.error('Error fetching users:', error); } } async function createAndLogUser() { console.log('\nAttempting to create a user...'); try { const response = await fetch('/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Charlie', email: 'charlie@example.com' }) }); const data = await response.json(); console.log('Created user (mocked):', data); } catch (error) { console.error('Error creating user:', error); } } fetchAndLogUsers(); createAndLogUser(); // In a testing environment, you would typically tear down mocks: // afterAll(() => { // mock.teardown(); // });
http-request-mock --version
Debug
Known issues
breakingVersion 2.0.0 introduced significant internal refactoring, including a new design structure, improved type declarations, and potentially altered API behaviors for advanced use cases or specific configurations. While core mocking methods like `mock.get()` remain, it's crucial to review the updated API documentation when migrating from 1.x versions.
fix
Consult the official documentation for v2.0.0+ to understand specific API changes, migration paths, and ensure compatibility with your existing mock configurations.
affects: >=2.0.0
gotchaAs `http-request-mock` intercepts low-level browser APIs (`XMLHttpRequest`, `fetch`) and Node.js network modules globally, it can potentially conflict with other libraries or testing frameworks that also modify these global objects. This can lead to unintended interactions or mocks not being applied.
fix
Ensure `mock.setup()` is called as early as possible in your application or test suite. Use `mock.teardown()` consistently, especially in `afterEach` or `afterAll` hooks in testing frameworks, to isolate mock effects and prevent leaks between tests.
affects: >=1.0.0
gotchaThe webpack plugin and command-line tool offered by `http-request-mock` provide powerful ways to manage mock data externally, but misconfiguration can lead to mocks not being applied, build failures, or unexpected runtime behavior.
fix
Thoroughly review the specific documentation for the Webpack plugin or CLI tool. Verify your `webpack.config.js` or CLI arguments correctly define mock file locations and options, especially in projects with complex build processes.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: mock.get is not a function
The `mock` object was not correctly imported as the default export, or `mock.setup()` was not called to initialize the interception layer before defining mocks.
fix
Ensure you are importing `mock` as `import mock from 'http-request-mock';` and that `mock.setup()` is invoked before attempting to define any request mocks (e.g., `mock.get()`, `mock.post()`).
Uncaught (in promise) TypeError: Failed to fetch (or similar Network Error)
Mocks are not active, either because `mock.setup()` wasn't called, the URL pattern defined in `mock.get()`/`mock.post()` doesn't precisely match the outgoing request, or a mock for the specific HTTP method is missing.
fix
Verify `mock.setup()` is called and executed. Carefully check the URL patterns (including query parameters, if applicable) and HTTP methods in your mock definitions to ensure they align exactly with the actual requests being made by your application.
Requests made in Node.js environment are not being intercepted
In Node.js, `http-request-mock` intercepts `http.request` and `https.request`. If your test runner or another library patches these global methods *after* `http-request-mock.setup()` is called, its interception might be bypassed.
fix
Ensure `http-request-mock.setup()` is invoked as early as possible in your Node.js application or test environment, ideally before any other modules that might modify native HTTP methods are loaded or initialized. Review module loading order if conflicts persist.
Upgrade
Version history
2.0.2latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
6 hits · last 30 days
node
6
Resources
http-request-mock — npm install http-request-mock · libregistry