HTTP Mock Server for Node.js

raw JSON →
2.7.18 verified Thu Apr 23 auth: no javascript

http-mockserver is a Node.js library designed for easily mocking HTTP servers, primarily used for testing purposes. It allows developers to define static or dynamic responses for specific HTTP methods and URIs on a given port. The current stable version is 2.7.21 (as of April 2026). The package appears to have a consistent maintenance cadence, with recent updates (as seen in the changelog for 2025-2026) focusing on dependency vulnerability fixes and minor bug fixes rather than new features or breaking changes. Key differentiators include its simplicity in defining mock endpoints, support for both static responses and dynamic request handlers (using Express-like `req`, `res` objects), and the ability to start a mock server either programmatically within a Node.js process or as a standalone CLI tool. The CLI option allows interaction from non-Node.js clients via a REST API. It also provides utilities for inspecting request logs and waiting for specific requests to simplify assertion logic in tests.

error Error: listen EADDRINUSE: address already in use :::8080
cause Attempting to add a mock or start a server on a port that is already in use by another process or a previous uncleaned mock server instance.
fix
Change the port number in your addMock call to an available port. Alternatively, ensure mockServer.clearAll() and mockServer.stop() are called in your test suite's afterAll or teardown hooks to prevent port conflicts.
error TypeError: mockServer.addMock is not a function
cause This error typically occurs if `mockServer` was not imported correctly, or if it was instantiated incorrectly (e.g., `new mockServer()` if `mockServer` is an object with static methods).
fix
Ensure you are using the correct named import: import { mockServer } from 'http-mockserver'; for ESM or const { mockServer } = require('http-mockserver'); for CommonJS. mockServer is an object, not a class.
error Error: Mocks cannot be added on port undefined
cause When using `mockServer.addMock()`, the `port` property is a mandatory part of the mock object, unless you are using an instance created by `mockServer.create(port)`.
fix
Explicitly define the port property within each mock object passed to mockServer.addMock({ port: 8080, ... }). If you want to avoid specifying the port repeatedly, use const myMockService = mockServer.create(8080); and then myMockService.addMock({ ... });.
gotcha The `http-mockserver` requires Node.js v16.20.2 or higher. Earlier Node.js versions may encounter compatibility issues or unfulfilled `engines` requirements during installation.
fix Ensure your Node.js environment meets the minimum version requirement (>=v16.20.2). Use `nvm` or `volta` to manage Node.js versions if necessary.
gotcha When using `mockServer.addMock()`, ensure the specified `port` is available. If another process is already listening on that port (e.g., 8080), the mock server will fail to bind, leading to an 'EADDRINUSE' error. The `mockServer.start()` method also defaults to port 3000, which can conflict.
fix Choose an unused port for your mocks, or implement logic to dynamically find an available port. Always clean up mocks with `mockServer.clearAll()` or `mockServer.stop()` in your test teardown to free up ports.
gotcha There's a distinction between `mockServer` (which manages all mocks) and `mockClient` (for interacting with an externally started server). If you're running `http-mockserver` as a standalone CLI process or using `mockServer.start()` in a separate Node process, you must use `mockClient` to add/remove mocks and retrieve logs from your main application.
fix If managing the mock server within the same process, use `mockServer`. If communicating with a remote or independently launched mock server, configure `mockClient.setServerHost()` and use its API methods.
npm install http-mockserver
yarn add http-mockserver
pnpm add http-mockserver

This quickstart demonstrates setting up both static and dynamic HTTP mocks on different ports using `http-mockserver`. It shows how to define responses with specific status codes, headers, and bodies, and how to use a handler function for more complex, stateful mocking. It also illustrates creating port-specific instances.

import { mockServer } from 'http-mockserver';

async function setupMocks() {
  // Start a mock server on a specific port (optional if using `mockServer.create`)
  // mockServer.start(8080); 

  // Static mock for a GET request
  mockServer.addMock({
    port: 8080,
    method: 'GET',
    uri: '/api/users/123',
    response: {
      statusCode: 200,
      headers: { 'Content-Type': 'application/json' },
      body: { id: 123, name: 'Alice Smith' }
    }
  });

  // Dynamic mock for a POST request with a counter
  let callCount = 0;
  mockServer.addMock({
    port: 8080,
    method: 'POST',
    uri: '/api/events',
    handler: (req, res) => {
      callCount++;
      console.log(`Event received. Current count: ${callCount}`);
      res.status(201).send({ message: `Event processed, call #${callCount}`, payload: req.body });
    }
  });

  console.log('Mock servers are set up on port 8080. Try curling:');
  console.log('curl http://localhost:8080/api/users/123');
  console.log('curl -X POST -H "Content-Type: application/json" -d \'{"type":"click"}\' http://localhost:8080/api/events');

  // Example of using a port-specific instance
  const authService = mockServer.create(8081);
  authService.addMock({
    uri: '/auth/token',
    method: 'POST',
    response: { statusCode: 200, body: { accessToken: 'mock-token' } }
  });
  console.log('Auth service mock also available on port 8081:');
  console.log('curl -X POST http://localhost:8081/auth/token');

  // To clean up after tests
  // mockServer.clearAll();
  // mockServer.stop(); // Only if mockServer.start was called
}

setupMocks();