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 install -D nock
yarn add -D nock
pnpm add -D nock
Import
import nock from 'nock';
Quick Example
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 responseAbout 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
| Package | nock |
| Category | Testing |
| Weekly Downloads | 3M+ |
| License | MIT |
| Install | npm install -D nock |
Related Packages
Mock Service Worker (MSW) is an API mocking library that uses the Service Worker API to intercept re…
Sinon.js provides standalone test spies, stubs, and mocks for JavaScript that work with any test fra…
SuperTest is a high-level HTTP assertion library built on SuperAgent that makes it easy to test Node…
Jest is a delightful JavaScript testing framework with a focus on simplicity, created by Facebook. I…
Axios is a promise-based HTTP client for the browser and Node.js that provides an elegant and powerf…
Browse npm Packages by Category
Explore our reference of 200 popular npm packages with install commands, examples, and quick-start guides.