Mockttp HTTP Mocking Server

4.3.1 · active · verified Sun Apr 19

Mockttp is a versatile JavaScript library for intercepting, transforming, and testing HTTP requests and responses. It serves as a powerful tool for integration testing by allowing developers to stub server responses, verify real HTTP requests, and even act as a transparent proxy for complex network debugging. Unlike in-process stubbing solutions, Mockttp operates at the network level, ensuring accurate testing of how entire stacks handle real-world HTTP traffic. The current stable version is v4.3.1, with major versions typically released on an annual cadence, focusing on modern Node.js environments and developer experience. Key differentiators include its ability to run tests uniformly in both Node.js and browser environments, support for transparent proxying and HTTPS interception (with built-in CA certificate generation), strong TypeScript typing, and features for safe, parallel test execution with enhanced debuggability.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates setting up a local Mockttp server with HTTPS, defining a POST rule with a delay and a WebSocket passthrough rule with request transformation, and starting the server.

import * as mockttp from 'mockttp';

async function runMockServer() {
  // Generate a CA certificate for HTTPS interception if needed
  // In a real test, you'd configure your client to trust this CA.
  const https = await mockttp.generateCACertificate();
  const server = mockttp.getLocal({ https });

  // Define a rule for a POST request to example.com
  server.forPost()
    .forHostname("example.com")
    .delay(500) // Introduce a 500ms delay
    .thenReply(200, "Hello world from Mockttp!");

  // Define a rule for any WebSocket connection with a specific cookie
  server.forAnyWebSocket()
    .withHeaders({ cookie: 'abcd' })
    .thenPassThrough({
      transformRequest: {
        matchReplaceQuery: [/username=(.*)/, 'role=admin&username=$1']
      }
    });

  await server.start();
  console.log(`Mock server started on port ${server.port}`);
  console.log('Intercepting example.com POST requests and transforming WebSockets.');

  // In a real application, you'd now run your client code that makes requests.
  // For demonstration, we'll keep the server running for a bit.
  setTimeout(async () => {
    await server.stop();
    console.log('Mock server stopped.');
  }, 10000);
}

runMockServer().catch(console.error);

view raw JSON →