or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

fixture-testing.mdglobal-management.mdindex.mdrecording-playback.mdrequest-interception.mdrequest-matching.mdresponse-definition.md
tile.json

tessl/npm-nock

HTTP server mocking and expectations library for Node.js testing environments

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/nock@14.0.x

To install, run

npx @tessl/cli install tessl/npm-nock@14.0.0

index.mddocs/

Nock

Nock is an HTTP server mocking and expectations library for Node.js that enables developers to test modules that perform HTTP requests in complete isolation. It intercepts HTTP/HTTPS requests to external services and allows you to define mock responses, making tests fast, deterministic, and independent of external network resources.

Package Information

  • Package Name: nock
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install nock

Core Imports

CommonJS:

const nock = require("nock");

ES modules (default import):

import nock from "nock";

ES modules (named imports - for TypeScript projects):

import nock, { 
  cleanAll, 
  activate, 
  isActive, 
  isDone, 
  pendingMocks, 
  activeMocks, 
  disableNetConnect, 
  enableNetConnect 
} from "nock";

Basic Usage

const nock = require("nock");

// Mock an HTTP GET request
const scope = nock("https://api.example.com")
  .get("/users/123")
  .reply(200, { id: 123, name: "John Doe" });

// Your code that makes the HTTP request will now receive the mock response
// After the request is made, verify it was called:
scope.done(); // Throws if the request wasn't made

Architecture

Nock is built around several key components:

  • Scopes: Define the base URL and common configuration for a group of interceptors
  • Interceptors: Specify request matching criteria and define mock responses
  • Global Control: Functions to manage nock's activation state and cleanup
  • Recording System: Capture real HTTP traffic for later playback as fixtures
  • Back Mode: Fixture-based testing workflow for integration with existing test suites

Capabilities

HTTP Request Interception

Core functionality for creating scopes and intercepting HTTP requests with flexible matching criteria.

function nock(basePath: string | RegExp | Url | URL, options?: Options): Scope;

Request Interception

Response Definition

Define mock responses with various data types, headers, and timing controls.

interface Interceptor {
  reply(statusCode?: number, body?: ReplyBody, headers?: ReplyHeaders): Scope;
  replyWithError(errorMessage: string | object): Scope;
  replyWithFile(statusCode: number, fileName: string, headers?: ReplyHeaders): Scope;
  delay(ms: number | DelayOptions): this;
}

Response Definition

Request Matching

Advanced request matching including headers, query parameters, and request bodies.

interface Scope {
  matchHeader(name: string, value: RequestHeaderMatcher): this;
  filteringPath(regex: RegExp, replace: string): this;
  filteringPath(fn: (path: string) => string): this;
  filteringRequestBody(regex: RegExp, replace: string): this;
  filteringRequestBody(
    fn: (body: string, recordedBody: string) => string
  ): this;
}

interface Interceptor {
  query(matcher: QueryMatcher): this;
  matchHeader(name: string, value: RequestHeaderMatcher): this;
  basicAuth(options: { user: string; pass?: string }): this;
}

Request Matching

Global Management

Control nock's global state, cleanup interceptors, manage network access, and load fixtures.

function cleanAll(): void;
function activate(): void;
function isActive(): boolean;
function isDone(): boolean;
function pendingMocks(): string[];
function activeMocks(): string[];
function disableNetConnect(): void;
function enableNetConnect(matcher?: string | RegExp | ((host: string) => boolean)): void;
function removeInterceptor(interceptor: Interceptor | ReqOptions): boolean;
function abortPendingRequests(): void;
function load(path: string): Scope[];
function loadDefs(path: string): Definition[];
function define(definitions: Definition[]): Scope[];

Global Management

Recording and Playback

Record real HTTP traffic and replay it as fixtures for testing.

interface Recorder {
  rec(options?: boolean | RecorderOptions): void;
  clear(): void;
  play(): string[] | Definition[];
}

const recorder: Recorder;
function restore(): void;

Recording and Playback

Fixture-Based Testing (Back Mode)

Advanced fixture-based testing workflow with multiple modes for different testing scenarios.

interface Back {
  (fixtureName: string, nockedFn: (nockDone: () => void) => void): void;
  (
    fixtureName: string,
    options: BackOptions,
    nockedFn: (nockDone: () => void) => void
  ): void;
  (fixtureName: string, options?: BackOptions): Promise<{
    nockDone: () => void;
    context: BackContext;
  }>;
  
  currentMode: BackMode;
  fixtures: string;
  setMode(mode: BackMode): void;
}

type BackMode = 'wild' | 'dryrun' | 'record' | 'update' | 'lockdown';

Fixture-Based Testing

Types

Core Types

interface Options {
  allowUnmocked?: boolean;
  reqheaders?: Record<string, RequestHeaderMatcher>;
  badheaders?: string[];
  filteringScope?: (scope: string) => boolean;
  encodedQueryParams?: boolean;
}

type RequestHeaderMatcher = string | RegExp | ((fieldValue: string) => boolean);
type RequestBodyMatcher = 
  | string 
  | Buffer 
  | RegExp 
  | DataMatcherArray 
  | DataMatcherMap 
  | ((body: any) => boolean);

type ReplyBody = string | Record<string, any> | Buffer | ReadStream;
type ReplyHeaders = 
  | Record<string, ReplyHeaderValue>
  | Map<string, ReplyHeaderValue>
  | ReplyHeaderValue[];

type ReplyHeaderValue = string | string[] | ReplyHeaderFunction;
type ReplyHeaderFunction = (
  req: ClientRequest,
  res: IncomingMessage,
  body: string | Buffer
) => string | string[];

Data Matching Types

type DataMatcher =
  | boolean
  | number
  | string
  | null
  | undefined
  | RegExp
  | DataMatcherArray
  | DataMatcherMap;

interface DataMatcherArray extends ReadonlyArray<DataMatcher> {}
interface DataMatcherMap {
  [key: string]: DataMatcher;
}

type QueryMatcher = 
  | boolean
  | string
  | DataMatcherMap
  | URLSearchParams
  | ((parsedObj: ParsedUrlQuery) => boolean);

Definition Types

interface Definition {
  scope: string | RegExp;
  path: string | RegExp;
  port?: number | string;
  method?: string;
  status?: number;
  body?: RequestBodyMatcher;
  reqheaders?: Record<string, RequestHeaderMatcher>;
  response?: ReplyBody;
  headers?: ReplyHeaders;
  options?: Options;
}

interface ReqOptions {
  hostname?: string;
  port?: number;
  method?: string;
  path?: string;
  proto?: string;
  headers?: Record<string, string>;
}

Events

Nock provides a global event emitter for monitoring request interception:

const emitter: NodeJS.EventEmitter;

Common events:

  • 'no match' - Emitted when a request doesn't match any interceptor

Error Handling

Nock throws specific errors in various scenarios:

Network Errors

  • NetConnectNotAllowedError: Thrown when disableNetConnect() is active and a request doesn't match any interceptor
    • Error code: ENETUNREACH
    • Message: "Nock: Disallowed net connect for..."

URL and Protocol Errors

  • TypeError: Thrown for invalid URLs or unsupported protocols
    • Invalid URL format: new URL() constructor errors
    • Unsupported protocol: Only HTTP/HTTPS are supported
    • Message example: "Protocol 'ftp:' not recognized..."

Interceptor Configuration Errors

  • Error: Thrown for invalid interceptor configurations
    • Missing method parameter: "The 'method' parameter is required for an intercept call"
    • Invalid path format: "Non-wildcard URL path strings must begin with a slash"
    • Duplicate query definitions: "Query parameters have already been defined"
    • Invalid status code: "Invalid undefined value for status code"

Scope Verification Errors

  • AssertionError: Thrown by scope.done() when interceptors haven't been satisfied
    • Message lists pending interceptors that weren't matched

File System Errors

  • Error: Thrown by fixture loading functions when fs is unavailable
    • Browser environments: "No fs" error from loadDefs()
    • Invalid file path: Standard fs.readFileSync() errors

JSON Parsing Errors

  • SyntaxError: Thrown when fixture files contain invalid JSON
  • Error: Thrown by define() for invalid definition format
    • Missing required fields: "Method is required"
    • Port conflicts: "Mismatched port numbers in scope and port properties"

Common Error Handling Patterns

try {
  const scope = nock("https://api.example.com")
    .get("/users")
    .reply(200, []);
    
  // Make request...
  
  scope.done(); // May throw AssertionError
} catch (error) {
  if (error.code === "ENETUNREACH") {
    console.log("Network request blocked by nock");
  } else if (error.name === "AssertionError") {
    console.log("Unused interceptors:", nock.pendingMocks());
  } else {
    throw error; // Re-throw unexpected errors
  }
}