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

HTTP Mocking Libraries

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

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
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 通过 Service Worker 在浏览器中拦截请求,能够模拟真实的网络环境,支持多种请求类型和动态响应。

  • sinon:

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

  • nock:

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

  • mockttp:

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

集成方式

  • msw:

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

  • sinon:

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

  • nock:

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

  • mockttp:

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

学习曲线

  • msw:

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

  • sinon:

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

  • nock:

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

  • mockttp:

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

性能

  • msw:

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

  • sinon:

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

  • nock:

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

  • mockttp:

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

社区支持

  • msw:

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

  • sinon:

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

  • nock:

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

  • mockttp:

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

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

  • msw:

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

  • sinon:

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

  • nock:

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

  • mockttp:

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

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)