mockttp vs msw vs nock vs sinon
HTTPモックライブラリ
mockttpmswnocksinon類似パッケージ:

HTTPモックライブラリ

HTTPモックライブラリは、APIとの通信をシミュレートするためのツールであり、テストや開発中に外部サービスに依存せずに動作を確認することができます。これにより、ネットワークの遅延や外部サービスの障害を気にせずに、アプリケーションの動作を確認できるため、開発効率が向上します。

npmのダウンロードトレンド

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
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リクエストを簡単にモックできる柔軟性を持っています。特定のリクエストに対して異なるレスポンスを返す設定が可能で、テストシナリオに応じた詳細な制御ができます。

  • msw:

    mswは、サービスワーカーを利用して、実際のAPIと同様の環境を構築できます。これにより、フロントエンドの開発中にリアルなレスポンスをシミュレートし、ユーザーインターフェースのテストが容易になります。

  • nock:

    nockは、Node.jsのHTTPリクエストをインターセプトし、特定のレスポンスを返す設定が簡単です。APIのエンドポイントをモックするのに最適で、特にバックエンドのテストに強力です。

  • sinon:

    sinonは、関数の振る舞いをモックするための強力な機能を提供します。HTTPリクエストのモックだけでなく、他の関数のスタブやスパイとしても利用でき、テストの柔軟性が高まります。

学習曲線

  • mockttp:

    mockttpは、シンプルなAPIを持ち、直感的に使用できるため、学習曲線が緩やかです。初心者でもすぐに使い始めることができます。

  • msw:

    mswは、サービスワーカーの概念を理解する必要がありますが、フロントエンド開発者にとっては比較的容易に学べるライブラリです。

  • nock:

    nockは、Node.jsのHTTPリクエストを扱うため、Node.jsに慣れている開発者にとっては学習が容易ですが、初めての人には少しハードルが高いかもしれません。

  • sinon:

    sinonは、スタブやスパイの概念を理解する必要がありますが、テストの柔軟性を高めるために非常に役立ちます。基本的な使い方は簡単ですが、応用には少し学習が必要です。

テストの一貫性

  • mockttp:

    mockttpは、HTTPリクエストを一貫してモックできるため、テストの結果が安定しやすいです。これにより、テストの信頼性が向上します。

  • msw:

    mswは、フロントエンドのテストにおいて、一貫したレスポンスを提供するため、ユーザーインターフェースのテスト結果が安定します。

  • nock:

    nockは、バックエンドのテストにおいて、一貫したHTTPリクエストのモックを提供し、テストの信頼性を確保します。

  • sinon:

    sinonは、関数の振る舞いをモックすることで、一貫したテスト結果を提供します。特に、複雑な依存関係を持つ関数のテストに役立ちます。

拡張性

  • mockttp:

    mockttpは、カスタムミドルウェアを追加することで、モックの動作を拡張することができます。特定のニーズに応じたカスタマイズが可能です。

  • msw:

    mswは、サービスワーカーを利用しているため、他のライブラリやフレームワークと組み合わせて使用することが容易です。

  • nock:

    nockは、Node.jsのエコシステムに組み込まれているため、他のNode.jsライブラリと簡単に統合できます。

  • sinon:

    sinonは、スタブやスパイの機能を持っているため、他のテストライブラリと組み合わせて使用することが可能で、柔軟なテスト環境を構築できます。

メンテナンス

  • mockttp:

    mockttpは、シンプルな設計により、メンテナンスが容易です。コードの可読性が高く、変更がしやすいです。

  • msw:

    mswは、サービスワーカーを使用しているため、フロントエンドのコードと密接に連携し、メンテナンスが容易です。

  • nock:

    nockは、Node.jsのHTTPリクエストをモックするため、Node.jsのエコシステムに適したメンテナンスが行いやすいです。

  • sinon:

    sinonは、テストのスタブやスパイを提供するため、テストコードのメンテナンスが容易で、テストの可読性が向上します。

選び方: mockttp vs msw vs nock vs sinon

  • mockttp:

    mockttpは、HTTPリクエストをモックするためのシンプルで強力なライブラリです。特に、非同期のテストや、複雑なHTTPインタラクションをシミュレートする必要がある場合に適しています。

  • msw:

    mswは、サービスワーカーを使用してAPIリクエストをモックするライブラリです。フロントエンドアプリケーションの開発中に、実際のAPIを使用することなく、リアルなレスポンスをシミュレートしたい場合に最適です。

  • 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