CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-mockttp

Mock HTTP server for testing HTTP clients and stubbing webservices

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

mock-server-setup.mddocs/

Mock Server Setup

Core server lifecycle management, configuration, and metadata access for creating and controlling Mockttp instances.

Capabilities

Server Factory Functions

Creates different types of Mockttp instances for various use cases.

/**
 * Get a Mockttp instance on the local machine.
 * In Node.js, creates an in-process MockttpServer.
 * In browsers, creates a MockttpClient that connects to an admin server.
 */
function getLocal(options?: MockttpOptions): Mockttp;

/**
 * Get a Mockttp instance controlled through a remote admin server.
 * Connects to a Mockttp admin server to create and manage mock servers.
 */
function getRemote(options?: MockttpClientOptions): Mockttp;

/**
 * Get a Mockttp admin server instance for managing multiple mock servers.
 * Used for programmatic admin server setup or with browser-based testing.
 */
function getAdminServer(options?: MockttpAdminServerOptions): MockttpAdminServer;

/**
 * Reset connections to admin servers.
 * Useful for cleaning up connections in test teardown.
 */
function resetAdminServer(): void;

Usage Examples:

import { getLocal, getRemote, getAdminServer } from "mockttp";

// Local server (most common for Node.js testing)
const mockServer = getLocal({
  cors: false,
  debug: true,
  https: {
    keyLength: 2048
  }
});

// Remote client (for browser testing)
const mockClient = getRemote({
  host: 'localhost',
  port: 45454
});

// Admin server (for coordinating multiple instances)
const adminServer = getAdminServer({
  port: 45454,
  cors: true
});

Server Lifecycle

Core methods for starting, stopping, and controlling mock servers.

interface Mockttp {
  /**
   * Start the mock server on the specified port or port range.
   * If no port specified, uses a random available port.
   */
  start(port?: number | PortRange): Promise<void>;
  
  /**
   * Stop the mock server and reset all rules and subscriptions.
   */
  stop(): Promise<void>;
  
  /**
   * Enable debug output for troubleshooting request matching and handling.
   */
  enableDebug(): void;
  
  /**
   * Reset stored rules and subscriptions without stopping the server.
   * Most cases should use stop() and start() instead.
   */
  reset(): void;
}

type PortRange = { startPort: number, endPort: number };

Usage Examples:

import { getLocal } from "mockttp";

const mockServer = getLocal();

// Start on random port
await mockServer.start();
console.log(`Server running on ${mockServer.url}`);

// Start on specific port
await mockServer.start(8080);

// Start with port range
await mockServer.start({ startPort: 8000, endPort: 8100 });

// Enable debugging
mockServer.enableDebug();

// Clean shutdown
await mockServer.stop();

Server Metadata

Properties for accessing server information and generating URLs.

interface Mockttp {
  /**
   * The root URL of the running server.
   * Throws error if accessed before server is started.
   */
  readonly url: string;
  
  /**
   * The port number the server is running on.
   * Throws error if accessed before server is started.
   */
  readonly port: number;
  
  /**
   * Environment variables for using the server as an HTTP/HTTPS proxy.
   * Throws error if accessed before server is started.
   */
  readonly proxyEnv: ProxyEnvConfig;
  
  /**
   * Generate a full URL for the given path on this server.
   * Throws error if accessed before server is started.
   */
  urlFor(path: string): string;
}

interface ProxyEnvConfig {
  HTTP_PROXY: string;
  HTTPS_PROXY: string;
}

Usage Examples:

import { getLocal } from "mockttp";

const mockServer = getLocal();
await mockServer.start();

// Access server metadata
console.log(`Server URL: ${mockServer.url}`);
console.log(`Server port: ${mockServer.port}`);
console.log(`API endpoint: ${mockServer.urlFor('/api/users')}`);

// Use as proxy
process.env = { ...process.env, ...mockServer.proxyEnv };

// Now HTTP requests will be proxied through the mock server

Configuration Options

Configuration interfaces for customizing server behavior.

interface MockttpOptions {
  /**
   * CORS configuration. 
   * Defaults to false for local servers, true for remote clients.
   */
  cors?: boolean | cors.CorsOptions;
  
  /**
   * Enable debug output for request matching and handling.
   */
  debug?: boolean;
  
  /**
   * HTTPS configuration for TLS interception and certificate management.
   */
  https?: MockttpHttpsOptions;
  
  /**
   * HTTP/2 support configuration.
   * true: use HTTP/2 for all supporting clients
   * 'fallback': use HTTP/2 only for clients that don't support HTTP/1.1
   * false: never use HTTP/2
   */
  http2?: true | 'fallback' | false;
  
  /**
   * SOCKS proxy support for unwrapping SOCKS connections.
   */
  socks?: boolean | SocksServerOptions;
  
  /**
   * Protocol passthrough rules for non-HTTP traffic.
   * 'unknown-protocol': pass through unrecognized protocols
   */
  passthrough?: Array<'unknown-protocol'>;
  
  /**
   * Show suggested Mockttp code for unmatched requests.
   * Useful for development but may confuse end users.
   */
  suggestChanges?: boolean;
  
  /**
   * Record traffic for getSeenRequests() method.
   * Set to false for high-traffic scenarios to save memory.
   */
  recordTraffic?: boolean;
  
  /**
   * Maximum body size to process in bytes.
   * Larger bodies become empty and won't match body matchers.
   */
  maxBodySize?: number;
}

interface MockttpHttpsOptions {
  /**
   * CA certificate for signing generated certificates.
   */
  ca?: string | Buffer;
  
  /**
   * Server certificate for HTTPS connections.
   */ 
  cert?: string | Buffer;
  
  /**
   * Private key for HTTPS connections.
   */
  key?: string | Buffer;
  
  /**
   * Path to certificate file (alternative to cert).
   */
  certPath?: string;
  
  /**
   * Path to private key file (alternative to key).
   */
  keyPath?: string;
  
  /**
   * Key length for generated certificates (default: 2048).
   */
  keyLength?: number;
  
  /**
   * Default domain for non-SNI TLS connections.
   */
  defaultDomain?: string;
  
  /**
   * Hostnames to pass through without TLS interception.
   * Wildcards supported: '*.example.com'
   */
  tlsPassthrough?: Array<{hostname: string}>;
  
  /**
   * Only intercept TLS for these hostnames, pass through all others.
   * Mutually exclusive with tlsPassthrough.
   */
  tlsInterceptOnly?: Array<{hostname: string}>;
  
  /**
   * TLS server configuration options.
   */
  tlsServerOptions?: {
    minVersion?: 'TLSv1.3' | 'TLSv1.2' | 'TLSv1.1' | 'TLSv1';
  };
}

interface MockttpClientOptions {
  /**
   * Admin server hostname (default: 'localhost').
   */
  host?: string;
  
  /**
   * Admin server port (default: 45454).
   */
  port?: number;
  
  /**
   * Use HTTPS for admin server connection.
   */
  https?: boolean;
}

interface MockttpAdminServerOptions {
  /**
   * Host to bind the admin server (default: 'localhost').
   */
  host?: string;
  
  /**
   * Port for the admin server (default: 45454).
   */
  port?: number;
  
  /**
   * CORS configuration for admin endpoints.
   */
  cors?: boolean | cors.CorsOptions;
  
  /**
   * Enable debug output for admin server operations.
   */
  debug?: boolean;
}

Usage Examples:

import { getLocal, getAdminServer } from "mockttp";

// Complex HTTPS configuration
const httpsServer = getLocal({
  debug: true,
  https: {
    keyLength: 4096,
    defaultDomain: 'localhost',
    tlsPassthrough: [
      { hostname: '*.googleapis.com' },
      { hostname: 'secure-api.example.com' }
    ],
    tlsServerOptions: {
      minVersion: 'TLSv1.2'
    }
  },
  http2: 'fallback',
  cors: {
    origin: ['http://localhost:3000', 'https://app.example.com'],
    credentials: true
  },
  maxBodySize: 1024 * 1024 * 10 // 10MB
});

await httpsServer.start();

// Admin server for browser testing
const adminServer = getAdminServer({
  port: 45455,
  cors: true,
  debug: true
});

await adminServer.start();

SOCKS Configuration

interface SocksServerOptions {
  /**
   * Authentication methods to accept.
   * Current supported methods depend on implementation.
   */
  authMethods?: string[];
}

Constants

/**
 * Default port for Mockttp admin servers.
 */
const DEFAULT_ADMIN_SERVER_PORT = 45454;

docs

certificate-management.md

event-monitoring.md

http-request-mocking.md

index.md

mock-server-setup.md

response-actions.md

websocket-mocking.md

tile.json