httpception

raw JSON →
4.0.1 verified Sat Apr 25 auth: no javascript

Version 4.0.1. A lightweight HTTP mocking library for Node.js that intercepts HTTP traffic during tests. It automatically restores the http module after each test (via a registered afterEach block) and fails if any mocks were not exercised. Supports both simple inline mocking and a callback-based approach for scoping. Differentiates from alternatives like nock by its automatic cleanup and integration with test frameworks.

error Error: No mock matched for GET http://example.com/notfound
cause The request URL does not match any defined mock.
fix
Check the request URL and method; ensure the mock definition is correct.
error AssertionError: expected false to be truthy
cause AfterEach callback detected unexercised mocks.
fix
Ensure all mocks are exercised during the test, or use callback form.
error TypeError: httpception is not a function
cause Incorrect import (e.g., using named import instead of default).
fix
Use require('httpception') or default import.
gotcha If the registered afterEach fails due to unexercised mocks, it can cause test framework issues.
fix Use the callback form to scope mocks explicitly: httpception({...}, () => { ... })
breaking Version 3.x dropped support for Node <6.0.0.
fix Upgrade Node to >=6.0.0 or stay on v2.x.
gotcha Mocked requests must match exactly including query parameters.
fix Use a function as request to ignore certain parts: request: { url: '/foo', method: 'GET', query: { bar: 'baz' } }
gotcha Mocks are not removed if an error is thrown synchronously before returning from the callback.
fix Ensure the callback returns the promise or handle errors properly.
npm install httpception
yarn add httpception
pnpm add httpception

Demonstrates basic HTTP mocking with automatic cleanup via afterEach block.

const httpception = require('httpception');
const got = require('got');
const assert = require('assert');

httpception({
  request: 'GET http://example.com/foobar',
  response: {
    statusCode: 200,
    headers: {
      'Content-Type': 'text/plain',
    },
    body: 'the text',
  },
});

get('example.com/foobar').then((response) => {
  assert.strictEqual(response.body, 'the text');
});