{"id":11406,"library":"nock","title":"Nock HTTP Mocking for Node.js","description":"Nock is a robust HTTP server mocking and expectations library designed specifically for Node.js environments. It enables developers to test modules that make outbound HTTP/HTTPS requests in isolation by intercepting network traffic and responding with predefined data. The current stable release series is v14, with v14.0.12 being the latest as of April 2026. An actively developed v15 beta series introduces new features such as `passthrough()` for granular control over unmocked requests and improved error handling, but is not yet recommended for production use due to an accidental v15.0.0 release that was later deprecated. Nock maintains an active release cadence, frequently publishing bug fixes and beta updates. Its key differentiators include comprehensive control over request matching (by host, path, query, body, headers, and HTTP verb), the ability to define repeatable or one-time responses, and functionalities for recording and playing back HTTP interactions using 'nock-back' for fixture-based testing. It aims to provide deep control over the network layer to facilitate reliable unit and integration testing without relying on actual network connectivity.","status":"active","version":"14.0.12","language":"javascript","source_language":"en","source_url":"https://github.com/nock/nock","tags":["javascript","typescript"],"install":[{"cmd":"npm install nock","lang":"bash","label":"npm"},{"cmd":"yarn add nock","lang":"bash","label":"yarn"},{"cmd":"pnpm add nock","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary Nock object is the default export. For CommonJS, `require('nock')` directly provides the `nock` object, not `require('nock').default`.","wrong":"const nock = require('nock').default;","symbol":"nock","correct":"import nock from 'nock';"},{"note":"Use `import type` for importing TypeScript types to prevent bundling issues and ensure types are stripped at compile time.","wrong":"import { Scope } from 'nock';","symbol":"Scope","correct":"import type { Scope } from 'nock';"},{"note":"Utility methods like `cleanAll`, `isDone`, `activate`, and `restore` are properties of the default `nock` object and are not named exports.","wrong":"import { cleanAll } from 'nock'; cleanAll();","symbol":"nock.cleanAll","correct":"nock.cleanAll();"}],"quickstart":{"code":"import nock from 'nock';\nimport { strict as assert } from 'node:assert';\n\n// Define the base URL for the API to mock\nconst API_BASE_URL = 'http://api.example.com';\nconst FAKE_API_PATH = '/users/123';\n\nasync function getUserData(userId: string) {\n  const response = await fetch(`${API_BASE_URL}/users/${userId}`, {\n    headers: { 'Accept': 'application/json' }\n  });\n  if (!response.ok) {\n    throw new Error(`HTTP error! Status: ${response.status}`);\n  }\n  return response.json();\n}\n\nasync function runTest() {\n  // 1. Set up the Nock interceptor for a GET request\n  const scope = nock(API_BASE_URL)\n    .matchHeader('Accept', 'application/json')\n    .get(FAKE_API_PATH)\n    .reply(200, { id: '123', name: 'Nock User', email: 'user@example.com' }, {\n      'Content-Type': 'application/json',\n      'X-Nock-Mocked': 'true',\n      'Cache-Control': 'no-cache'\n    });\n\n  try {\n    // 2. Make the HTTP request that Nock will intercept\n    console.log('Fetching user data...');\n    const userData = await getUserData('123');\n\n    // 3. Assert the response data matches the mock\n    assert.deepStrictEqual(userData, {\n      id: '123',\n      name: 'Nock User',\n      email: 'user@example.com'\n    }, 'User data should match mock payload.');\n    console.log('Successfully received mocked user data.');\n\n    // 4. Assert that all Nock expectations were met for this scope\n    assert(scope.isDone(), 'Nock scope should be done, all expectations met.');\n    console.log('Nock expectations met for the defined scope.');\n\n  } catch (error) {\n    console.error('Test failed:', error);\n    process.exit(1);\n  } finally {\n    // 5. Clean up Nock mocks to prevent interference with other tests\n    nock.cleanAll();\n    console.log('Nock mocks cleaned up.');\n  }\n}\n\n// Ensure Nock is active; often implicit after import, but good for clarity\nnock.activate();\n\nrunTest();\n","lang":"typescript","description":"This quickstart demonstrates how to mock an HTTP GET request using Nock. It sets up an interceptor for a specific URL, path, and header, defines a mock JSON response, makes a request using `fetch`, and then asserts both the received data and that all Nock expectations were met for that specific scope, finally cleaning up the mocks."},"warnings":[{"fix":"Downgrade to the latest v14 stable version or specify a v15 beta version in your `package.json`.","message":"Nock v15.0.0 was released by accident and contains known issues. It has been immediately deprecated. Users should avoid installing v15.0.0 directly and instead continue using the latest v14 stable releases (e.g., v14.0.12) or explicitly use the v15 beta series (e.g., v15.0.0-beta.10) for pre-release features.","severity":"breaking","affected_versions":"15.0.0"},{"fix":"Ensure your Node.js environment meets the minimum requirement of `>=18.20.0 <20 || >=20.12.1` as specified in the package's `engines` field.","message":"Nock now strictly enforces Node.js engine compatibility. Versions older than Node.js 18.20.0 or specific patches within Node.js 20 may not be supported, potentially leading to runtime errors or unexpected behavior.","severity":"breaking","affected_versions":">=14.0.0"},{"fix":"Refactor calls to `replyWithError(errorObject)` to ensure `errorObject` is an instance of `Error` (e.g., `new Error('Something went wrong')`).","message":"When using `replyWithError()`, Nock v14.0.10 and later expect an actual `Error` object as the argument, not a plain JavaScript object. Providing a plain object will no longer be treated as an error and may lead to unexpected behavior.","severity":"breaking","affected_versions":">=14.0.10"},{"fix":"Add `afterEach(() => nock.cleanAll());` to your test suite setup to ensure a clean state before each test.","message":"Nock interceptors are active immediately upon creation. To prevent unintended side effects or test pollution, always call `nock.cleanAll()` in your test teardown hooks (e.g., `afterEach`, `afterAll`) to remove all pending and active mocks.","severity":"gotcha","affected_versions":"all"},{"fix":"Use `nock.enableNetConnect('localhost')` or `nock.enableNetConnect('*.my-real-service.com')` to allow specified hostnames to make real network requests.","message":"By default, Nock intercepts all HTTP/HTTPS requests once activated. If you need to allow specific 'real' network requests (e.g., to a local API or specific external services) while mocking others, you must explicitly configure `nock.enableNetConnect()`.","severity":"gotcha","affected_versions":"all"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Carefully review the `nock` definition and the actual outgoing request. Use `nock.pendingMocks()` to identify unmatched scopes or `nock.on('request')` and `nock.recorder.rec()` for debugging mismatch details. Ensure all parameters (host, path, method, query, body, headers) align exactly.","cause":"The actual outgoing HTTP request did not precisely match any defined Nock interceptor's criteria (URL, path, method, headers, query, or body).","error":"Nock: No match for request"},{"fix":"For CommonJS, use `const nock = require('nock');`. For ESM, ensure `import nock from 'nock';` is used, as `nock` is the default export. Methods like `cleanAll()` are accessed via `nock.cleanAll()`.","cause":"This typically occurs in CommonJS environments if `require('nock').default` is used instead of `require('nock')`, or if `nock` is mistakenly treated as a named import in some ESM setups.","error":"TypeError: nock is not a function"},{"error":"Error: Aborted"},{"fix":"Verify that `nock` mocks are responding within expected timeframes. If using `delay()` or `delayConnection()`, adjust them or ensure your test runner's fake timers (e.g., `jest.runAllTimers()`) are correctly advancing.","cause":"A mocked request either timed out waiting for a Nock response, or the Nock interceptor itself has a `delayConnection()` or `delay()` option set that is longer than the client's timeout, or fake timers are not advanced.","error":"ETIMEDOUT"},{"fix":"Ensure `nock.activate()` has been called. If the mock should apply to multiple requests, add `.persist()` to the interceptor definition. Check `nock.isDone()` before assertions to confirm all mocks were consumed, or `nock.pendingMocks()` for unfulfilled expectations. Reconfirm the URL/path of the request and mock.","cause":"This usually indicates that `nock` was not active, the specific mock was already consumed (not persistent), or the request was not intercepted by Nock at all, leading to a real network request (which then failed).","error":"Error: Request failed with status code 404 (or other non-mocked status)"}],"ecosystem":"npm"}