msw README

The project's README from github.com/mswjs/msw. As one markdown file: README.md.


The Mock Service Worker logo

Mock Service Worker

Industry standard API mocking for JavaScript.

Join our Discord server



Features


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

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?

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 Workleap Chromatic
StackBlitz CodeRabbit

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)

Special thanks

Thank you to Blacksmith for a x10 faster remote builds.

CI powered by Blacksmith

msw (mswjs/msw)

Searching Database…

18.3K ·GitHub
这是做什么用的?Mock Service Worker(MSW)是 JavaScript 领域业界标准的 API mock 库。它会拦截你的应用发出的网络请求,返回你预先定义好的模拟响应,因此完全不会碰到真实的后端。
它是一个测试框架,还是我在应用里用的库?它是添加到 JavaScript 项目里的一个库,不是测试运行器或框架:你需要编写请求拦截规则(handler),在浏览器里通过 setupWorker 注册,在 Node.js 里通过 setupServer 注册。
我怎么把它加到我的项目里?README 指向官方文档和它的 Quick start 指南作为入门起点。简单来说:安装 msw 包,编写 handler,然后在浏览器里通过 setupWorker(或在 Node 里通过 setupServer)注册。
运行它需要额外装什么吗?按照包的 engines 字段要求,需要 Node.js 18 或更高版本。不需要任何账号或托管服务——它就是一个 npm 依赖,另外 graphql 作为运行时依赖随包提供,用于 mock GraphQL API。
使用这些 mock 需要修改我的应用代码吗?不需要——请求是在网络层面被拦截的,也就是在离开你的应用之后,所以应用代码和测试完全感知不到哪些请求被 mock 了。你甚至可以在浏览器的 Network 面板里查看被 mock 的响应。
这是给谁用的——真的经过生产环境验证吗?面向构建或测试 API 的前端和后端 JavaScript 开发者。数十万工程师在使用它,其中包括 Google、Microsoft、Spotify、Amazon 和 Netflix 的团队。
它只能在浏览器里用,还是 Node.js 里也能用?都可以。在浏览器里,它会注册一个真正的 Service Worker;在 Node.js 里(Service Worker 并不存在),它会切换到一种底层拦截算法——同一套请求拦截规则在两种环境下都能使用。
我怎么编写 mock——有没有专门的 DSL?没有——handler 使用类似 Express 的路由语法。你可以用参数、通配符或正则表达式来匹配请求,并返回自定义的状态码、请求头、cookie、延迟,或者完全自定义的处理函数。
同一套 mock 能同时用于单元测试、集成测试和 E2E 测试吗?可以,这正是它的核心设计目标:一份 mock 定义可以同时用于本地开发、调试以及单元/集成/E2E 测试,不需要任何适配器——而且你的测试完全感知不到有东西被 mock 了。
它支持 GraphQL 和 WebSocket API 吗,还是只支持 REST?不止 REST:README 的课程列表涵盖了 mock REST 和 GraphQL API,以及 mock 和测试 WebSocket API,而且 graphql 是这个包的运行时依赖。
MSW 是免费的吗?是的——它采用 MIT 许可证,完全免费。该项目依靠 GitHub Sponsors 运营,设有金、银、铜三个赞助等级,此外关于 MSW 的付费 Egghead 课程所得的版费也用于支持项目的持续开发。
What are similar projects?pollyjs, Mock, nock, mockito, jsdom, hoppscotch, testify, mocha
Creator
mswjs
Size
13.9 MB
Stars
18.3K
Age
7y
Commits · 90 Days