• Stars
    star
    738
  • Rank 59,448 (Top 2 %)
  • Language
    TypeScript
  • License
    Apache License 2.0
  • Created over 7 years ago
  • Updated 30 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Powerful friendly HTTP mock server & proxy library

Mockttp Build Status Available on NPM Try Mockttp on RunKit

Part of HTTP Toolkit: powerful tools for building, testing & debugging HTTP(S)

Mockttp lets you intercept, transform or test HTTP requests & responses in JavaScript - quickly, reliably & anywhere.

You can use Mockttp for integration testing, by intercepting real requests as part of your test suite, or you can use Mockttp to build custom HTTP proxies that capture, inspect and/or rewrite HTTP in any other kind of way you like.

HTTP testing is the most common and well supported use case. There's a lot of tools to test HTTP, but typically by stubbing the HTTP functions in-process at the JS level. That ties you to a specific environment, doesn't truly test the real requests that you code would send, and only works for requests made in the same JS process. It's inflexible, limiting and inaccurate, and often unreliable & tricky to debug too.

Mockttp meanwhile allows you to do accurate true integration testing, writing one set of tests that works out of the box in node or browsers, with support for transparent proxying & HTTPS, strong typing & promises throughout, fast & safe parallel testing, and with debuggability built-in at every stage.

Mockttp is also battle-tested as a scriptable rewriting proxy, powering all the HTTP internals of HTTP Toolkit. Anything you can do with HTTP Toolkit, you can automate with Mockttp as a headless script.

Features

Let's get specific. Mockttp lets you:

  • Write easy, fast & reliable node.js & browser HTTP integration tests
  • Stub server responses and verify HTTP requests
  • Intercept HTTPS too, with built-in self-signed certificate generation
  • Mock requests inside or outside your process/tab, including subprocesses, native code, remote devices, and more
  • Test true real-world behaviour, verifying the real requests made, and testing exactly how your whole stack will handle a response in reality
  • Stub direct requests as a mock server, or transparently stub requests sent elsewhere as an HTTP mocking proxy
  • Mock HTTP in both node & browser tests with the same code (universal/'isomorphic' HTTP mocking)
  • Safely mock HTTP in parallel, with autoconfiguration of ports, mock URLs and proxy settings, for super-charged integration testing
  • Debug your tests easily, with full explainability of all mock matches & misses, mock autosuggestions, and an extra detailed debug mode
  • Write modern test code, with promises all the way down, async/await, and strong typing (with TypeScript) throughout

Get Started

npm install --save-dev mockttp

Get Testing

To run an HTTP integration test, you need to:

  • Start a Mockttp server
  • Mock the endpoints you're interested in
  • Make some real HTTP requests
  • Assert on the results

Here's a simple minimal example of all that using plain promises, Mocha, Chai & Superagent, which works out of the box in Node and modern browsers:

const superagent = require("superagent");
const mockServer = require("mockttp").getLocal();

describe("Mockttp", () => {
    // Start your mock server
    beforeEach(() => mockServer.start(8080));
    afterEach(() => mockServer.stop());

    it("lets you mock requests, and assert on the results", async () => {
        // Mock your endpoints
        await mockServer.forGet("/mocked-path").thenReply(200, "A mocked response");

        // Make a request
        const response = await superagent.get("http://localhost:8080/mocked-path");

        // Assert on the results
        expect(response.text).to.equal("A mocked response");
    });
});

(Want to play with this yourself? Try running a standalone version live on RunKit: https://npm.runkit.com/mockttp)

That is pretty easy, but we can make this simpler & more powerful. Let's take a look at some more fancy features:

const superagent = require("superagent");
require('superagent-proxy')(superagent);
const mockServer = require("mockttp").getLocal();

describe("Mockttp", () => {
    // Note that there's no start port here, so we dynamically find a free one instead
    beforeEach(() => mockServer.start());
    afterEach(() => mockServer.stop());

    it("lets you mock without specifying a port, allowing parallel testing", async () => {
        await mockServer.forGet("/mocked-endpoint").thenReply(200, "Tip top testing");

        // Try mockServer.url or .urlFor(path) to get a the dynamic URL for the server's port
        let response = await superagent.get(mockServer.urlFor("/mocked-endpoint"));

        expect(response.text).to.equal("Tip top testing");
    });

    it("lets you verify the request details the mockttp server receives", async () => {
        const endpointMock = await mockServer.forGet("/mocked-endpoint").thenReply(200, "hmm?");

        await superagent.get(mockServer.urlFor("/mocked-endpoint"));

        // Inspect the mock to get the requests it received and assert on their details
        const requests = await endpointMock.getSeenRequests();
        expect(requests.length).to.equal(1);
        expect(requests[0].url).to.equal(`http://localhost:${mockServer.port}/mocked-endpoint`);
    });

    it("lets you proxy requests made to any other hosts", async () => {
        // Match a full URL instead of just a path to mock proxied requests
        await mockServer.forGet("http://google.com").thenReply(200, "I can't believe it's not google!");

        // One of the many ways to use a proxy - this assumes Node & superagent-proxy.
        // In a browser, you can simply use the browser settings instead.
        let response = await superagent.get("http://google.com").proxy(mockServer.url);

        expect(response.text).to.equal("I can't believe it's not google!");
    });
});

These examples use Mocha, Chai and Superagent, but none of those are required: Mockttp will work with any testing tools that can handle promises (and with minor tweaks, many that can't), and can mock requests from any library, tool or device you might care to use.

Documentation

Credits

More Repositories

1

httptoolkit

HTTP Toolkit is a beautiful & open-source tool for debugging, testing and building with HTTP(S) on Windows, Linux & Mac ๐ŸŽ‰ Open an issue here to give feedback or ask for help.
2,431
star
2

react-reverse-portal

React reparenting โš›๏ธ Build an element once, move it anywhere
JavaScript
849
star
3

frida-interception-and-unpinning

Frida scripts to directly MitM all HTTPS traffic from a target mobile application
JavaScript
834
star
4

httptoolkit-desktop

Electron wrapper to build and distribute HTTP Toolkit for the desktop
TypeScript
568
star
5

httptoolkit-android

Automatic Android interception & debugging with HTTP Toolkit, for Android
Java
428
star
6

httptoolkit-server

The backend of HTTP Toolkit
JavaScript
424
star
7

mockrtc

Powerful friendly WebRTC mock peer & proxy
TypeScript
274
star
8

httptoolkit-ui

The UI of HTTP Toolkit
TypeScript
264
star
9

brotli-wasm

A reliable compressor and decompressor for Brotli, supporting node & browsers via wasm
TypeScript
245
star
10

android-ssl-pinning-demo

A tiny demo Android app using SSL pinning to block HTTPS MitM interception
Kotlin
79
star
11

httptoolkit-website

The main website of HTTP Toolkit: beautiful, cross-platform & open-source tools to debug, test and develop with HTTP(S).
JavaScript
67
star
12

jvm-http-proxy-agent

A JVM agent that automatically forces a proxy for HTTP(S) connections and trusts MitM certificates, for all major JVM HTTP clients
Java
58
star
13

docker-registry-facade

A tiny self-hostable Docker Registry facade - own your image URL without running your own registry
Dockerfile
45
star
14

mockipfs

Powerful friendly IPFS mock node & proxy
TypeScript
38
star
15

read-tls-client-hello

A pure-JS module to read TLS client hello data and calculate TLS fingerprints from an incoming socket connection.
TypeScript
31
star
16

docker-socks-tunnel

A tiny Dockerized SOCKS5 proxy
Dockerfile
26
star
17

mockthereum

Powerful friendly Ethereum mock node & proxy
TypeScript
26
star
18

mockttp-proxy-demo

A tiny demo, showing how to build your own scriptable HTTPS-intercepting proxy with Mockttp
JavaScript
22
star
19

browser-launcher

Detect the browser versions available on your system, and launch them in an isolated profile for automation & testing purposes.
JavaScript
18
star
20

openapi-directory-js

Building & bundling https://github.com/APIs-guru/openapi-directory for easy use from JS
TypeScript
18
star
21

mobx-shallow-undo

Zero-config undo & redo for Mobx
TypeScript
17
star
22

httpolyglot

Serve http and https connections over the same port with node.js
TypeScript
14
star
23

frida-js

Pure-JS bindings to control Frida from node.js & browsers
TypeScript
9
star
24

mockrtc-extension-example

An example web extension, using MockRTC to intercept & debug your own WebRTC traffic
TypeScript
9
star
25

accounts

The API & dashboard that power HTTP Toolkit account management
TypeScript
9
star
26

httpsnippet

HTTP Request snippet generator for many languages & libraries
JavaScript
7
star
27

ios-ssl-pinning-demo

A tiny demo iOS app using SSL pinning to block HTTPS MitM interception
Swift
6
star
28

http-encoding

Everything you need to handle HTTP message body content-encoding
TypeScript
4
star
29

osx-find-executable

Find an app's executable by its bundle id
JavaScript
4
star
30

mac-system-proxy

Access the Mac system proxy settings from Node.js
TypeScript
4
star
31

os-proxy-config

Access the operating system proxy configuration from Node.js, for all platforms
TypeScript
4
star
32

webextension

A browser extension used in HTTP Toolkit
TypeScript
3
star
33

node-launcher

WIP: An node.js-powered launcher for httptoolkit (try 'npx httptoolkit')
JavaScript
3
star
34

anonymizing-reverse-proxy

Anonymizing reverse proxy used between HTTP Toolkit end users & 3rd party services
Dockerfile
3
star
35

websocket-stream

websockets with the node stream API
JavaScript
3
star
36

act-build-base

A base image for local GitHub Action builds with Act
Shell
3
star
37

android.httptoolkit.tech

Static site used as infrastructure to support the HTTP Toolkit Android app
2
star
38

ipfs-openapi-spec

An IPFS OpenAPI spec, automatically generated from the official documentation
TypeScript
2
star
39

evil-package

An npm package demonstrating how packages can steal your data (but not actually doing so!)
JavaScript
2
star
40

testserver

A public test server for HTTP & related protocols, similar to httpbin.org (but actively maintained)
TypeScript
2
star
41

destroyable-server

A tiny Node.js module to make any net.Server force-closeable
TypeScript
1
star
42

amiusing

Microsite to tell you if you're currently being proxied by HTTP Toolkit
HTML
1
star
43

statuspagestatuspage

TypeScript
1
star
44

windows-system-proxy

Access the Windows system proxy settings from Node.js.
TypeScript
1
star
45

xz-decompress

XZ decompression for the browser & Node without native code, via WebAssembly
JavaScript
1
star