Installations
npm install mockttp
Developer
Developer Guide
Module System
CommonJS, ESM, UMD
Min. Node Version
>=14.14.0
Typescript Support
Yes
Node Version
20.11.1
NPM Version
10.2.4
Statistics
787 Stars
1,231 Commits
88 Forks
11 Watching
12 Branches
25 Contributors
Updated on 27 Nov 2024
Languages
TypeScript (99.31%)
JavaScript (0.69%)
Total Downloads
Cumulative downloads
Total Downloads
12,434,198
Last day
2%
27,733
Compared to previous day
Last week
12.8%
140,159
Compared to previous week
Last month
57.7%
521,549
Compared to previous month
Last year
-21.6%
3,820,304
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
42
Dev Dependencies
59
Mockttp
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
1npm 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:
1const superagent = require("superagent"); 2const mockServer = require("mockttp").getLocal(); 3 4describe("Mockttp", () => { 5 // Start your mock server 6 beforeEach(() => mockServer.start(8080)); 7 afterEach(() => mockServer.stop()); 8 9 it("lets you mock requests, and assert on the results", async () => { 10 // Mock your endpoints 11 await mockServer.forGet("/mocked-path").thenReply(200, "A mocked response"); 12 13 // Make a request 14 const response = await superagent.get("http://localhost:8080/mocked-path"); 15 16 // Assert on the results 17 expect(response.text).to.equal("A mocked response"); 18 }); 19});
(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:
1const superagent = require("superagent"); 2require('superagent-proxy')(superagent); 3const mockServer = require("mockttp").getLocal(); 4 5describe("Mockttp", () => { 6 // Note that there's no start port here, so we dynamically find a free one instead 7 beforeEach(() => mockServer.start()); 8 afterEach(() => mockServer.stop()); 9 10 it("lets you mock without specifying a port, allowing parallel testing", async () => { 11 await mockServer.forGet("/mocked-endpoint").thenReply(200, "Tip top testing"); 12 13 // Try mockServer.url or .urlFor(path) to get a the dynamic URL for the server's port 14 let response = await superagent.get(mockServer.urlFor("/mocked-endpoint")); 15 16 expect(response.text).to.equal("Tip top testing"); 17 }); 18 19 it("lets you verify the request details the mockttp server receives", async () => { 20 const endpointMock = await mockServer.forGet("/mocked-endpoint").thenReply(200, "hmm?"); 21 22 await superagent.get(mockServer.urlFor("/mocked-endpoint")); 23 24 // Inspect the mock to get the requests it received and assert on their details 25 const requests = await endpointMock.getSeenRequests(); 26 expect(requests.length).to.equal(1); 27 expect(requests[0].url).to.equal(`http://localhost:${mockServer.port}/mocked-endpoint`); 28 }); 29 30 it("lets you proxy requests made to any other hosts", async () => { 31 // Match a full URL instead of just a path to mock proxied requests 32 await mockServer.forGet("http://google.com").thenReply(200, "I can't believe it's not google!"); 33 34 // One of the many ways to use a proxy - this assumes Node & superagent-proxy. 35 // In a browser, you can simply use the browser settings instead. 36 let response = await superagent.get("http://google.com").proxy(mockServer.url); 37 38 expect(response.text).to.equal("I can't believe it's not google!"); 39 }); 40});
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
- Many thanks to https://github.com/vieiralucas for donating the package name!
No vulnerabilities found.
Reason
10 commit(s) and 5 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: Apache License 2.0: LICENSE:0
Reason
Found 2/21 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/ci.yml:1
- Info: no jobLevel write permissions found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:13: update your workflow using https://app.stepsecurity.io/secureworkflow/httptoolkit/mockttp/ci.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:15: update your workflow using https://app.stepsecurity.io/secureworkflow/httptoolkit/mockttp/ci.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/ci.yml:27: update your workflow using https://app.stepsecurity.io/secureworkflow/httptoolkit/mockttp/ci.yml/main?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/ci.yml:23
- Info: 0 out of 2 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 third-party GitHubAction dependencies pinned
- Info: 0 out of 1 npmCommand dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'main'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 11 are checked with a SAST tool
Score
4.4
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to mockttp
@kronoslive/mockttp
Mock HTTP server for testing HTTP clients and stubbing webservices
@httptoolkit/subscriptions-transport-ws
A websocket transport for GraphQL subscriptions
@nosecurity/mockttp
Mock HTTP server for testing HTTP clients and stubbing webservices
@sanperrier/mockttp
Mock HTTP server for testing HTTP clients and stubbing webservices (forked)