HTTP Request Mocking Library
raw JSON →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.
Common errors
error TypeError: mock.get is not a function ↓
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()). error Uncaught (in promise) TypeError: Failed to fetch (or similar Network Error) ↓
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. error Requests made in Node.js environment are not being intercepted ↓
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. Warnings
breaking Version 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. ↓
gotcha As `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. ↓
gotcha The 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. ↓
Install
npm install http-request-mock yarn add http-request-mock pnpm add http-request-mock Imports
- mock wrong
const mock = require('http-request-mock')correctimport mock from 'http-request-mock' - MockOptions wrong
import { MockOptions } from 'http-request-mock'correctimport type { MockOptions } from 'http-request-mock' - MockItem wrong
import { MockItem } from 'http-request-mock'correctimport type { MockItem } from 'http-request-mock'
Quickstart
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();
// });