Nock HTTP Mocking for Node.js

14.0.12 · active · verified Sun Apr 19

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import nock from 'nock';
import { strict as assert } from 'node:assert';

// Define the base URL for the API to mock
const API_BASE_URL = 'http://api.example.com';
const FAKE_API_PATH = '/users/123';

async function getUserData(userId: string) {
  const response = await fetch(`${API_BASE_URL}/users/${userId}`, {
    headers: { 'Accept': 'application/json' }
  });
  if (!response.ok) {
    throw new Error(`HTTP error! Status: ${response.status}`);
  }
  return response.json();
}

async function runTest() {
  // 1. Set up the Nock interceptor for a GET request
  const scope = nock(API_BASE_URL)
    .matchHeader('Accept', 'application/json')
    .get(FAKE_API_PATH)
    .reply(200, { id: '123', name: 'Nock User', email: 'user@example.com' }, {
      'Content-Type': 'application/json',
      'X-Nock-Mocked': 'true',
      'Cache-Control': 'no-cache'
    });

  try {
    // 2. Make the HTTP request that Nock will intercept
    console.log('Fetching user data...');
    const userData = await getUserData('123');

    // 3. Assert the response data matches the mock
    assert.deepStrictEqual(userData, {
      id: '123',
      name: 'Nock User',
      email: 'user@example.com'
    }, 'User data should match mock payload.');
    console.log('Successfully received mocked user data.');

    // 4. Assert that all Nock expectations were met for this scope
    assert(scope.isDone(), 'Nock scope should be done, all expectations met.');
    console.log('Nock expectations met for the defined scope.');

  } catch (error) {
    console.error('Test failed:', error);
    process.exit(1);
  } finally {
    // 5. Clean up Nock mocks to prevent interference with other tests
    nock.cleanAll();
    console.log('Nock mocks cleaned up.');
  }
}

// Ensure Nock is active; often implicit after import, but good for clarity
nock.activate();

runTest();

view raw JSON →