介绍

欢迎阅读 Mock Service Worker 文档!

Mock Service Worker (MSW) 是用于浏览器和 Node.js 的 API 模拟库。使用 MSW,你可以拦截传出的请求,观察它们,并使用模拟响应对它们做出响应。

¥Mock Service Worker (MSW) is an API mocking library for browser and Node.js. With MSW, you can intercept outgoing requests, observe them, and respond to them using mocked responses.

MSW 的与众不同之处在于它大力提倡独立的 API 模拟层,为你的网络行为创建单一事实来源并将其集成到你使用的任何工具中。这会导致更具弹性的设置,并与其他库功能配对,从而创建真正无缝的 API 模拟体验。

¥What sets MSW apart is that it heavily advocates for a standalone API mocking layer, creating a single source of truth for your network behavior and integrating it across whichever tools you’re using. This leads to a more resilient setup and, paired with other library features, creates a truly seamless API mocking experience.

Mock REST and GraphQL APIs with Mock Service Worker

Watch our video course

Learn to control the network with MSW in our new Egghead course.

特性

¥Features

不可知

¥Agnostic

MSW 旨在完全与环境、框架和工具无关。你可以在任何浏览器或 Node.js 进程中使用它,而无需额外的配置、适配器或插件。它适用于所有请求客户端,无论是原生 window.fetch() 还是第三方库,如 Axios、React Query 或 Apollo。

¥MSW is designed to be fully environment-, framework- and tool-agnostic. You can use it in any browser or Node.js process without additional configurations, adapters, or plugins. It works with all request clients, be it a native window.fetch() or third-party libraries like Axios, React Query, or Apollo.

无缝

¥Seamless

MSW 使用 Service Worker API 在网络级别拦截实际生产请求。MSW 没有修补 fetch 并干扰应用的完整性,而是押注平台,利用标准浏览器 API 实现革命性的请求拦截逻辑。

¥MSW uses the Service Worker API to intercept actual production requests on the network level. Instead of patching fetch and meddling with your application’s integrity, MSW bets on the platform, utilizing the standard browser API to implement a revolutionary request interception logic.

即使在 Node.js 中,没有标准的拦截请求的方法,MSW 也使用类扩展而不是模块修补来确保你的测试在尽可能接近生产的环境中运行。

¥Even in Node.js, where there are no standard means to intercept requests, MSW uses class extension instead of module patching to ensure your tests run in the environment as close to production as possible.

可重复使用

¥Reusable

通过将 API 模拟视为独立层,MSW 可以集成到整个堆栈中,允许你根据需要重用和自定义网络行为。想象一下在开发、集成和端到端测试期间使用相同的 API 模拟,然后在你的 Storybook 或现场演示期间使用相同的 API 模拟。好吧,有了 MSW,你就可以。

¥By treating API mocking as a standalone layer, MSW can integrate throughout your entire stack, allowing you to reuse and customize network behavior on demand. Imagine using the same API mocks during development, integration and end-to-end testing, and then in your Storybook or during a live demo. Well, with MSW, you can.

从这里开始

¥Start here

如果你以前从未尝试过 MSW 或不确定从哪里开始,请查看入门教程:

¥If you have never tried MSW before or unsure where to start, look no further than the Getting started tutorial:

Getting started

Three steps to get started with Mock Service Worker.