HTTP Request Mocking Library

raw JSON →
2.0.2 verified Thu Apr 23 auth: no javascript

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.

error TypeError: mock.get is not a function
cause 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()).
error Uncaught (in promise) TypeError: Failed to fetch (or similar Network Error)
cause 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.
error Requests made in Node.js environment are not being intercepted
cause 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.
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.
fix Consult the official documentation for v2.0.0+ to understand specific API changes, migration paths, and ensure compatibility with your existing mock configurations.
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.
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.
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.
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.
npm install http-request-mock
yarn add http-request-mock
pnpm add http-request-mock

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();
// });