mockttp vs msw vs nock vs sinon
HTTP Mocking Libraries
mockttpmswnocksinon类似的npm包:

HTTP Mocking Libraries

HTTP Mocking Libraries 主要用于在开发和测试过程中模拟 HTTP 请求和响应。这些库能够帮助开发者在不依赖真实后端服务的情况下进行前端开发和测试,从而提高开发效率和测试的可靠性。它们各自有不同的功能和设计理念,适用于不同的场景和需求。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
mockttp08841.98 MB417 天前Apache-2.0
msw018,2106.05 MB372 个月前MIT
nock013,127185 kB1002 个月前MIT
sinon09,7582.52 MB662 个月前BSD-3-Clause

功能对比: mockttp vs msw vs nock vs sinon

模拟能力

  • mockttp:

    mockttp 提供了强大的 HTTP 请求和响应模拟能力,支持异步处理,可以轻松模拟复杂的 API 交互。

  • msw:

    MSW 通过 Service Worker 在浏览器中拦截请求,能够模拟真实的网络环境,支持多种请求类型和动态响应。

  • nock:

    nock 专注于 Node.js 环境,能够拦截和模拟 HTTP 请求,支持多种 HTTP 方法和状态码,适合后端开发和测试。

  • sinon:

    sinon 提供了灵活的模拟和间谍功能,可以用于 HTTP 请求的模拟,也可以用于其他函数的行为测试,适合需要多种测试策略的场景。

集成方式

  • mockttp:

    mockttp 可以轻松集成到 Node.js 应用中,提供简单的 API 来启动和配置模拟服务器,适合快速开发和测试。

  • msw:

    MSW 通过在浏览器中使用 Service Worker 进行集成,能够无缝与前端框架(如 React、Vue)结合,适合现代前端开发。

  • nock:

    nock 作为 Node.js 的一个库,直接与请求库(如 axios、request)集成,适合后端测试和开发。

  • sinon:

    sinon 是一个独立的测试库,可以与其他测试框架(如 Mocha、Jest)结合使用,适合需要多种测试工具的项目。

学习曲线

  • mockttp:

    mockttp 的学习曲线相对较平缓,提供了清晰的文档和示例,适合初学者快速上手。

  • msw:

    MSW 的学习曲线也较为友好,尤其是对于熟悉现代前端开发的开发者,能够快速理解其用法。

  • nock:

    nock 的学习曲线稍陡,特别是对于不熟悉 Node.js 的开发者,但其强大的功能弥补了这一点。

  • sinon:

    sinon 的学习曲线相对较高,因为它提供了丰富的功能和选项,适合需要深入测试的开发者。

性能

  • mockttp:

    mockttp 在性能上表现良好,能够处理高并发的请求模拟,适合需要高效测试的场景。

  • msw:

    MSW 的性能依赖于浏览器的能力,能够高效地处理网络请求,适合前端开发中的实时测试。

  • nock:

    nock 在 Node.js 环境中表现出色,能够快速拦截和响应请求,适合后端服务的测试。

  • sinon:

    sinon 的性能取决于测试的复杂性,通常在简单的模拟场景中表现良好,但在复杂场景中可能会影响测试速度。

社区支持

  • mockttp:

    mockttp 拥有活跃的社区支持,提供了丰富的文档和示例,适合开发者获取帮助。

  • msw:

    MSW 作为一个流行的库,拥有广泛的社区支持和活跃的开发,文档详细且易于理解。

  • nock:

    nock 是一个成熟的库,拥有稳定的社区支持,文档齐全,适合长期使用。

  • sinon:

    sinon 拥有强大的社区支持,广泛应用于各种测试场景,文档和示例丰富,适合深入学习和使用。

如何选择: mockttp vs msw vs nock vs sinon

  • mockttp:

    选择 mockttp 如果你需要一个轻量级的 HTTP 服务器模拟工具,支持异步请求和响应,并且希望能够在 Node.js 环境中轻松集成。它适合进行快速的 API 测试和开发。

  • msw:

    选择 MSW(Mock Service Worker)如果你希望在浏览器中拦截网络请求并进行模拟,适合用于前端开发和测试,能够与真实的浏览器环境无缝集成,支持 REST 和 GraphQL。

  • nock:

    选择 nock 如果你需要在 Node.js 中进行 HTTP 请求的模拟,特别是在单元测试中。它能够拦截 HTTP 请求并提供自定义响应,适合用于测试后端服务的交互。

  • sinon:

    选择 sinon 如果你需要一个全面的测试库,支持模拟、间谍和桩功能。它不仅可以用于 HTTP 请求的模拟,还可以用于其他类型的函数和对象的测试,适合需要复杂测试场景的项目。

mockttp的README

Mockttp Build Status Available on NPM

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 your 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");
    });
});

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 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