Mockttp HTTP Mocking Server
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
-
TypeError: mockttp.getLocal is not a function
cause Attempting to use `require('mockttp').getLocal()` in an environment where Mockttp is primarily detected as an ES module or when using incorrect CommonJS import syntax.fixEnsure you are using the correct import style for your module system: `import { getLocal } from 'mockttp';` for ESM, or `const mockttp = require('mockttp'); const server = mockttp.getLocal();` for CJS. -
TypeError: server.get is not a function
cause Using the deprecated `get()` method (or `post()`, `anyRequest()`) on the mock server instance, which was removed in v3.0.0.fixUpdate your code to use the modern, explicit rule definition methods: `server.forGet()`, `server.forPost()`, `server.forAnyRequest()`, etc. -
The 'mockttp' package requires Node.js version >=20.0.0.
cause Your Node.js environment version is older than the minimum required by Mockttp v4.x.x.fixUpgrade your Node.js installation to version 20.0.0 or newer. Use a Node Version Manager (like nvm) to easily switch versions. -
Error: self signed certificate in certificate chain
cause Your client is not trusting the self-signed HTTPS certificate generated by Mockttp when it's intercepting secure traffic.fixConfigure your HTTP client (e.g., `process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'` for Node.js, or add the generated CA certificate to your client's trust store) or operating system to explicitly trust Mockttp's CA certificate.
Warnings
- breaking Mockttp v4.0.0 and above require Node.js v20.0.0 or higher. Running on older Node.js versions will result in an error.
- breaking With the release of v3.0.0, Mockttp dropped support for Node.js v12. The new minimum Node.js version is v14.14.0.
- breaking All rule definition methods that did not start with `.for[...]()` (e.g., `mockServer.get()`, `mockServer.post()`, `mockServer.anyRequest()`) were removed in v3.0.0. These were deprecated in v2.5.0.
- breaking Asynchronous body decoding is required for some content encodings (e.g., Brotli, Zstandard) since v2.0.0. Using synchronous properties like `body.decodedBuffer`, `body.text`, `body.json`, or `body.formData` may no longer decode content correctly or efficiently.
- gotcha When intercepting HTTPS traffic, Mockttp generates a self-signed CA certificate. For your client (e.g., browser, `fetch`, `axios`) to trust the intercepted traffic, you must explicitly configure it to trust this generated certificate.
Install
-
npm install mockttp -
yarn add mockttp -
pnpm add mockttp
Imports
- * as mockttp
const mockttp = require('mockttp');import * as mockttp from 'mockttp';
- { getLocal, getRemote }
import mockttp, { getLocal } from 'mockttp';import { getLocal, getRemote } from 'mockttp'; - getLocal
const { getLocal } = require('mockttp');const mockServer = require('mockttp').getLocal();
Quickstart
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);