{"id":17698,"library":"http-request-mock","title":"HTTP Request Mocking Library","description":"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.","status":"active","version":"2.0.2","language":"javascript","source_language":"en","source_url":"https://github.com/huturen/http-request-mock","tags":["javascript","xhr mock","XMLHttpRequest mock","xhr-mock","fetch mock","fetch-mock","wx.request mock","response mock","ajax mock","typescript"],"install":[{"cmd":"npm install http-request-mock","lang":"bash","label":"npm"},{"cmd":"yarn add http-request-mock","lang":"bash","label":"yarn"},{"cmd":"pnpm add http-request-mock","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary API surface is exposed as the default export, commonly aliased as `mock`. This allows access to setup, teardown, and request mocking methods.","wrong":"const mock = require('http-request-mock')","symbol":"mock","correct":"import mock from 'http-request-mock'"},{"note":"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.","wrong":"import { MockOptions } from 'http-request-mock'","symbol":"MockOptions","correct":"import type { MockOptions } from 'http-request-mock'"},{"note":"This type defines the structure of an individual mock configuration. Use `import type` for type-only imports.","wrong":"import { MockItem } from 'http-request-mock'","symbol":"MockItem","correct":"import type { MockItem } from 'http-request-mock'"}],"quickstart":{"code":"import mock from 'http-request-mock';\n\n// Initialize the mocking library to intercept requests\nmock.setup();\n\n// Mock a GET request to /api/users with a static JSON response\nmock.get('/api/users', (req) => {\n  console.log('Intercepted GET /api/users request:', req.url);\n  return {\n    status: 200,\n    headers: { 'Content-Type': 'application/json' },\n    body: JSON.stringify([\n      { id: 1, name: 'Alice', email: 'alice@example.com' },\n      { id: 2, name: 'Bob', email: 'bob@example.com' }\n    ])\n  };\n}, { delay: 500 }); // Simulate network latency with a 500ms delay\n\n// Mock a POST request to /api/users with a dynamic response based on request body\nmock.post('/api/users', (req) => {\n  const newUser = JSON.parse(req.body);\n  console.log('Intercepted POST /api/users request with data:', newUser);\n  return {\n    status: 201,\n    headers: { 'Content-Type': 'application/json' },\n    body: JSON.stringify({ id: Math.floor(Math.random() * 1000) + 3, ...newUser })\n  };\n});\n\n// Simulate client-side requests using fetch\nasync function fetchAndLogUsers() {\n  console.log('\\nAttempting to fetch users...');\n  try {\n    const response = await fetch('/api/users');\n    const data = await response.json();\n    console.log('Fetched users (mocked):', data);\n  } catch (error) {\n    console.error('Error fetching users:', error);\n  }\n}\n\nasync function createAndLogUser() {\n  console.log('\\nAttempting to create a user...');\n  try {\n    const response = await fetch('/api/users', {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json' },\n      body: JSON.stringify({ name: 'Charlie', email: 'charlie@example.com' })\n    });\n    const data = await response.json();\n    console.log('Created user (mocked):', data);\n  } catch (error) {\n    console.error('Error creating user:', error);\n  }\n}\n\nfetchAndLogUsers();\ncreateAndLogUser();\n\n// In a testing environment, you would typically tear down mocks:\n// afterAll(() => {\n//   mock.teardown();\n// });","lang":"typescript","description":"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."},"warnings":[{"fix":"Consult the official documentation for v2.0.0+ to understand specific API changes, migration paths, and ensure compatibility with your existing mock configurations.","message":"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.","severity":"breaking","affected_versions":">=2.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"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()`).","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.","error":"TypeError: mock.get is not a function"},{"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.","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.","error":"Uncaught (in promise) TypeError: Failed to fetch (or similar Network Error)"},{"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.","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.","error":"Requests made in Node.js environment are not being intercepted"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}