🧪
Testing3M+/wkMIT

nock

Nock is an HTTP server mocking and expectations library for Node.js that intercepts outgoing HTTP requests at the network level and returns predefined responses

Installation

npm
npm install -D nock
yarn
yarn add -D nock
pnpm
pnpm add -D nock

Import

ESM
import nock from 'nock';

Quick Example

usage
import nock from 'nock';

nock('https://api.example.com')
  .get('/users')
  .reply(200, [{ id: 1, name: 'John' }]);

// Now any HTTP GET to api.example.com/users
// returns the mocked response

About nock

Nock is an HTTP server mocking and expectations library for Node.js that intercepts outgoing HTTP requests at the network level and returns predefined responses. Unlike approaches that mock the HTTP client library itself, Nock overrides Node.js's http.request and https.request functions, intercepting all HTTP traffic regardless of which HTTP client library (axios, node-fetch, got, superagent) is used to make the request. Nock allows you to define interceptors that match requests by URL, HTTP method, request headers, query parameters, and request body, then respond with specific status codes, headers, and response bodies. The library supports recording real HTTP interactions and replaying them in tests, simulating network errors and timeouts, defining sequential responses for the same endpoint, and setting up persistent interceptors for frequently called endpoints. Nock is essential for unit testing code that makes HTTP requests, ensuring tests are fast, deterministic, and independent of external services. The library's matching system supports exact strings, regular expressions, and custom filter functions for flexible request matching.

Quick Facts

Packagenock
CategoryTesting
Weekly Downloads3M+
LicenseMIT
Installnpm install -D nock

Related Packages

Browse npm Packages by Category

Explore our reference of 200 popular npm packages with install commands, examples, and quick-start guides.