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

HTTPモックライブラリ

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

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

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
msw11,127,05517,6844.87 MB5121日前MIT
sinon9,598,1289,7642.22 MB522ヶ月前BSD-3-Clause
nock5,925,42813,084185 kB8222日前MIT
mockttp342,2448501.84 MB404ヶ月前Apache-2.0

機能比較: msw vs sinon vs nock vs mockttp

モックの柔軟性

  • msw:

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

  • sinon:

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

  • nock:

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

  • mockttp:

    mockttpは、複雑なHTTPリクエストを簡単にモックできる柔軟性を持っています。特定のリクエストに対して異なるレスポンスを返す設定が可能で、テストシナリオに応じた詳細な制御ができます。

学習曲線

  • msw:

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

  • sinon:

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

  • nock:

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

  • mockttp:

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

テストの一貫性

  • msw:

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

  • sinon:

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

  • nock:

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

  • mockttp:

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

拡張性

  • msw:

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

  • sinon:

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

  • nock:

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

  • mockttp:

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

メンテナンス

  • msw:

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

  • sinon:

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

  • nock:

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

  • mockttp:

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

選び方: msw vs sinon vs nock vs mockttp

  • msw:

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

  • sinon:

    sinonは、スタブ、スパイ、モックを提供するテストライブラリで、HTTPリクエストのモックだけでなく、関数の振る舞いをテストする際にも使用できます。より広範なテストシナリオをカバーしたい場合に適しています。

  • nock:

    nockは、Node.jsのHTTPリクエストをモックするためのライブラリで、特にバックエンドのテストに強みを持っています。HTTPリクエストのインターセプトや、特定のレスポンスを返す設定が容易です。

  • mockttp:

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

msw のREADME


The Mock Service Worker logo

Mock Service Worker

Industry standard API mocking for JavaScript.

Join our Discord server



Features

  • Seamless. A dedicated layer of requests interception at your disposal. Keep your application's code and tests unaware of whether something is mocked or not.
  • Deviation-free. Request the same production resources and test the actual behavior of your app. Augment an existing API, or design it as you go when there is none.
  • Familiar & Powerful. Use Express-like routing syntax to intercept requests. Use parameters, wildcards, and regular expressions to match requests, and respond with necessary status codes, headers, cookies, delays, or completely custom resolvers.

"I found MSW and was thrilled that not only could I still see the mocked responses in my DevTools, but that the mocks didn't have to be written in a Service Worker and could instead live alongside the rest of my app. This made it silly easy to adopt. The fact that I can use it for testing as well makes MSW a huge productivity booster."

Kent C. Dodds

Documentation

This README will give you a brief overview of the library, but there's no better place to start with Mock Service Worker than its official documentation.

Examples

Courses

We've partnered with Egghead to bring you quality paid materials to learn the best practices of API mocking on the web. Please give them a shot! The royalties earned from them help sustain the project's development. Thank you.

Browser

How does it work?

In-browser usage is what sets Mock Service Worker apart from other tools. Utilizing the Service Worker API, which can intercept requests for the purpose of caching, Mock Service Worker responds to intercepted requests with your mock definition on the network level. This way your application knows nothing about the mocking.

Take a look at this quick presentation on how Mock Service Worker functions in a browser:

What is Mock Service Worker?

How is it different?

  • This library intercepts requests on the network level, which means after they have been performed and "left" your application. As a result, the entirety of your code runs, giving you more confidence when mocking;
  • Imagine your application as a box. Every API mocking library out there opens your box and removes the part that does the request, placing a blackbox in its stead. Mock Service Worker leaves your box intact, 1-1 as it is in production. Instead, MSW lives in a separate box next to yours;
  • No more stubbing of fetch, axios, react-query, you-name-it;
  • You can reuse the same mock definition for the unit, integration, and E2E testing. Did we mention local development and debugging? Yep. All running against the same network description without the need for adapters or bloated configurations.

Usage example

// 1. Import the library.
import { http, HttpResponse } from 'msw'
import { setupWorker } from 'msw/browser'

// 2. Describe network behavior with request handlers.
const worker = setupWorker(
  http.get('https://github.com/octocat', ({ request, params, cookies }) => {
    return HttpResponse.json(
      {
        message: 'Mocked response',
      },
      {
        status: 202,
        statusText: 'Mocked status',
      },
    )
  }),
)

// 3. Start mocking by starting the Service Worker.
await worker.start()

Performing a GET https://github.com/octocat request in your application will result into a mocked response that you can inspect in your browser's "Network" tab:

Chrome DevTools Network screenshot with the request mocked

Tip: Did you know that although Service Worker runs in a separate thread, your request handlers execute entirely on the client? This way you can use the same languages, like TypeScript, third-party libraries, and internal logic to create the mocks you need.

Node.js

How does it work?

There's no such thing as Service Workers in Node.js. Instead, MSW implements a low-level interception algorithm that can utilize the very same request handlers you have for the browser. This blends the boundary between environments, allowing you to focus on your network behaviors.

How is it different?

  • Does not stub fetch, axios, etc. As a result, your tests know nothing about mocking;
  • You can reuse the same request handlers for local development and debugging, as well as for testing. Truly a single source of truth for your network behavior across all environments and all tools.

Usage example

Here's an example of using Mock Service Worker while developing your Express server:

import express from 'express'
import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'

const app = express()
const server = setupServer()

app.get(
  '/checkout/session',
  server.boundary((req, res) => {
    // Describe the network for this Express route.
    server.use(
      http.get(
        'https://api.stripe.com/v1/checkout/sessions/:id',
        ({ params }) => {
          return HttpResponse.json({
            id: params.id,
            mode: 'payment',
            status: 'open',
          })
        },
      ),
    )

    // Continue with processing the checkout session.
    handleSession(req, res)
  }),
)

This example showcases server.boundary() to scope request interception to a particular closure, which is extremely handy!

Sponsors

Mock Service Worker is trusted by hundreds of thousands of engineers around the globe. It's used by companies like Google, Microsoft, Spotify, Amazon, Netflix, and countless others. Despite that, it remains a hobby project maintained in a spare time and has no opportunity to financially support even a single full-time contributor.

You can change that! Consider sponsoring the effort behind one of the most innovative approaches around API mocking. Raise a topic of open source sponsorships with your boss and colleagues. Let's build sustainable open source together!

Golden sponsors

Become our golden sponsor and get featured right here, enjoying other perks like issue prioritization and a personal consulting session with us.

Learn more on our GitHub Sponsors profile.


GitHub Codacy Workleap Chromatic
StackBlitz

Silver sponsors

Become our silver sponsor and get your profile image and link featured right here.

Learn more on our GitHub Sponsors profile.


Replay Codemod Ryan Magoon

Bronze sponsors

Become our bronze sponsor and get your profile image and link featured in this section.

Learn more on our GitHub Sponsors profile.


Materialize Trigger.dev Vital

Awards & mentions

We've been extremely humbled to receive awards and mentions from the community for all the innovation and reach Mock Service Worker brings to the JavaScript ecosystem.

Technology Radar

Solution Worth Pursuing

Technology Radar (2020–2021)

Open Source Awards 2020

The Most Exciting Use of Technology

Open Source Awards (2020)