Esta página se muestra en inglés. Una traducción al español está en curso.
ScriptsApr 26, 2026·3 min de lectura

Nock — HTTP Server Mocking and Expectations for Node.js

HTTP server mocking and expectations library for Node.js that intercepts outgoing requests for deterministic API testing.

Introduction

Nock intercepts outgoing HTTP requests from Node.js at the http/https module level and returns predefined responses, eliminating the need for live API servers during testing. It lets you define expectations about which endpoints your code calls, what headers and bodies it sends, and what responses it should receive. This makes tests fast, deterministic, and independent of external service availability.

What Nock Does

  • Intercepts HTTP and HTTPS requests made by Node.js standard library modules
  • Returns configured status codes, headers, and response bodies without hitting the network
  • Supports request matching by URL, path, query parameters, headers, and body content
  • Records real HTTP traffic and replays it in future test runs
  • Raises errors when unexpected requests are made, enforcing strict API contracts

Architecture Overview

Nock works by monkey-patching Node.js's http.ClientRequest at the module level. When your code makes an HTTP request, Nock's interceptor checks its registry of defined mocks for a matching URL, method, and optional body or header matchers. If a match is found, the mock response is returned synchronously without opening a real socket. Interceptors are consumed after use by default, ensuring each expected call happens exactly once unless explicitly configured to persist.

Self-Hosting & Configuration

  • Install as a dev dependency: npm install --save-dev nock
  • Import and define interceptors before the code under test makes HTTP calls
  • Use nock.cleanAll() in afterEach hooks to reset interceptors between tests
  • Enable recording mode with nock.recorder.rec() to capture real traffic for replay
  • Set nock.disableNetConnect() to ensure no real HTTP requests leak during tests

Key Features

  • Request matching by URL, method, headers, query strings, and request body
  • Record and playback mode for capturing live API responses as fixtures
  • Scope-based interceptors that are consumed after use to enforce call counts
  • Regex and function-based matchers for dynamic URL and body patterns
  • Works with any HTTP client built on Node.js core — axios, got, node-fetch, etc.

Comparison with Similar Tools

  • MSW (Mock Service Worker) — intercepts at the network level and works in browsers too; Nock is Node.js-only but lighter
  • Sinon.JS — provides general-purpose stubs and spies; Nock specializes in HTTP mocking with richer request matching
  • Miragejs — browser-focused API mocking with an ORM layer; Nock targets Node.js server-side testing
  • WireMock — Java-based HTTP mock server; Nock runs in-process without a separate server
  • Polly.js — record/replay HTTP interactions; Nock offers similar recording plus stricter request expectations

FAQ

Q: Does Nock work with fetch in Node.js? A: Yes, if your Node.js version uses the built-in undici-based fetch. For older versions using node-fetch, Nock works transparently since node-fetch uses http internally.

Q: Can I mock the same endpoint multiple times? A: Yes. Chain .times(n) to allow n calls, or use .persist() to keep the interceptor active indefinitely.

Q: How do I verify that all expected requests were made? A: Call scope.isDone() after your test — it returns true only if all defined interceptors were consumed.

Q: Does Nock support GraphQL? A: Yes. Match POST requests to your GraphQL endpoint and use body matchers to verify query strings or variables.

Sources

Discusión

Inicia sesión para unirte a la discusión.
Aún no hay comentarios. Sé el primero en compartir tus ideas.

Activos relacionados