入门
开始使用 Mock Service Worker 的三个步骤。
开发者将 MSW 用于许多事情:在测试中模拟 API、在开发时调试网络、跨团队展示他们的工作、监控传出流量等。编写一个适合所有这些用例的教程相当困难。不过,也有好消息。无论你决定如何使用 MSW 以及在何处使用它,使用 MSW 都遵循相同的流程。
¥Developers use MSW for many things: to mock APIs in testing, to debug network while developing, to present their work across teams, to monitor the outgoing traffic, etc. Writing a single tutorial that would suit all those use cases is rather difficult. There’s good news, however. Working with MSW follows the same flow, no matter how and where you decide to use it.
下面,你可以找到一个完整的、基本的教程,该教程将 MSW 集成到 Node.js 应用中。请注意,本教程旨在作为工作参考,我们鼓励你按照下面每个部分中的附加链接来实现你想要的集成。
¥Below, you can find a complete, barebones tutorial that integrates MSW in a Node.js application. Please note that this tutorial is intended as a working reference, and you are encouraged to follow the additional links in each of the sections below to achieve the integration you want.
步骤 1:安装
¥Step 1: Install
通过在项目中运行以下命令将 MSW 安装为依赖:
¥Install MSW as a dependency by running the following command in your project:
npm install msw@latest --save-dev
如果需要,你也可以使用 从 CDN 安装 MSW。
¥If you need to, you can also install MSW from a CDN.
步骤 2:描述
¥Step 2: Describe
接下来,你使用 请求处理程序(例如 http.get()
、graphql.query()
)描述网络。请求处理程序负责 拦截请求 和 处理其响应,它们可以是模拟响应、真实响应和模拟的组合,或者什么都不是(如果你只想监控流量而不影响它)。
¥Next, you describe the network using Request handlers (e.g. http.get()
, graphql.query()
). A request handler is responsible for intercepting a request and handling its response, which can be a mocked response, a combination of the real response and a mock, or nothing, if you only want to monitor the traffic without affecting it.
在本教程中,让我们为 GET https://example.com/user
请求定义一个 HTTP 请求处理程序,并使用模拟 JSON 响应对其进行响应。
¥In this tutorial, let’s define a single HTTP request handler for a GET https://example.com/user
request and respond to it with a mocked JSON response.
// src/mocks/handlers.js
import { http, HttpResponse } from 'msw'
export const handlers = [
// Intercept "GET https://example.com/user" requests...
http.get('https://example.com/user', () => {
// ...and respond to them using this JSON response.
return HttpResponse.json({
id: 'c7b3d8e0-5e0b-4b0f-8b3a-3b9f4b3d3b3d',
firstName: 'John',
lastName: 'Maverick',
})
}),
]
从包含整个网络描述的单个
handlers.js
模块开始。随着时间的推移,你可以 重构处理程序 并学习如何 在运行时覆盖它们。¥Start small with a single
handlers.js
module that contains the entire network description. With time, you can restructure your handlers and learn how to override them on runtime.
你可以描述不同的 API,如 REST 或 GraphQL,同时包含在同一个 handlers
数组中。了解有关使用 MSW 描述服务器 API 的更多信息:
¥You can describe different APIs, like REST or GraphQL, including at the same time in the same handlers
array. Learn more about describing server APIs with MSW:
Describing REST API
Learn about describing RESTful APIs.
Describing GraphQL API
Learn about describing GraphQL APIs.
你可以通过注释请求处理程序 使用 TypeScript 来充分利用 MSW。当你拥有由实际 API 生成的类型定义时,这特别方便,无论是 OpenAPI 文档还是 GraphQL 代码生成器。
¥You can make the most out of MSW by annotating your request handlers using TypeScript. This is particularly handy when you have type definitions generated by your actual API, be it an OpenAPI document or GraphQL Code Generator.
步骤 3:集成
¥Step 3: Integrate
MSW 可与任何框架、请求库和其他工具集成,因为它可应用于环境级别,这意味着你只需决定是在浏览器中还是在 Node.js 进程中使用它(或两者兼而有之)。无论你处于什么环境,你仍然(重新)使用相同的请求处理程序。
¥MSW integrates with any frameworks, request libraries, and other tools because it applies itself on the environment level, which means you only have to decide whether you want to use it in the browser or in a Node.js process (or both). You still (re)use the same request handlers regardless of the environment you are in.
在本教程中,让我们通过创建一个名为 node.js
的 Node.js 集成模块将 MSW 集成到普通的 Node.js 进程中:
¥For this tutorial, let’s integrate MSW into a plain Node.js process by creating a Node.js integration module called node.js
:
// src/mocks/node.js
import { setupServer } from 'msw/node'
import { handlers } from './handlers'
export const server = setupServer(...handlers)
我们建议创建依赖于环境的集成模块,如
node.js
和browser.js
,以便你可以在不同的工具中重用相同的集成。JavaScript 中的任何工具都可以在浏览器(实际浏览器、Playwright、Cypress、Storybook)或 Node.js(Vitest、Jest、React Native)中运行。根据你的工具环境引入正确的集成,一切就绪。¥We recommend creating environment-dependent integration modules, like
node.js
andbrowser.js
, so you can reuse the same integrations across different tools. Any tooling in JavaScript runs either in the browser (actual browsers, Playwright, Cypress, Storybook) or in Node.js (Vitest, Jest, React Native). Pull in the right integration based on your tool’s environment, and you are all set.
我们创建的 node.js
集成模块将 MSW 配置为在任何 Node.js 进程中运行,但实际上尚未启动它。要启动请求拦截,你需要在 Node.js 进程中调用 server.listen()
:
¥The node.js
integration module we’ve created configures MSW to run in any Node.js process but doesn’t actually start it just yet. To start the request interception, you need to call server.listen()
in your Node.js process:
// src/index.js
import { server } from './mocks/node'
server.listen()
// This is a simple Node.js application that
// does a network request and prints the response.
async function app() {
const response = await fetch('https://example.com/user')
const user = await response.json()
console.log(user)
}
app()
你还可以根据
process.env.NODE_ENV
或任何其他标准有条件地启动 MSW。¥You can also start MSW conditionally, based on
process.env.NODE_ENV
or any other criteria.
运行应用现在将打印模拟响应而无需实际发出网络请求:
¥Running the application will now print the mocked response without actually making a network request:
node ./src/index.js
{
id: 'c7b3d8e0-5e0b-4b0f-8b3a-3b9f4b3d3b3d',
firstName: 'John',
lastName: 'Maverick'
}
了解有关将 MSW 集成到不同环境的更多信息:
¥Learn more about integrating MSW into different environments:
Browser
Integrate MSW in a browser environment, such as a React application or Storybook.
Node.js
Integrate MSW in Node.js, such as an Express application or a test runner.
React Native
Integrate MSW in a React Native application.
示例
¥Examples
在下面的存储库中,你可以找到如何使用 Mock Service Worker 和 Jest、Vitest、Cypress、Playwright、Angular、Svelte、Remix 等工具的实用、完整和简约示例。将 MSW 与这些工具集成时,请将它们用作参考。
¥In the repository below, you can find the functional, complete, and minimalistic examples of how to use Mock Service Worker with tools like Jest, Vitest, Cypress, Playwright, Angular, Svelte, Remix, and others. Use them as a reference whenever integrating MSW with those tools.
Usage examples
Examples of Mock Service Worker usage with various frameworks and libraries.
如果遇到问题,请将每个使用示例转换为复制存储库!
¥Turn each usage example into a reproduction repository if you encounter an issue!
需要帮助吗?
¥Need help?
开始使用新工具可能很困难,但你不必独自经历这一切。每当你遇到问题时,最好的去处就是我们的调试运行手册:
¥Starting with a new tool can be difficult but you don’t have go through that alone. Whenever you encounter an issue, the best place to go is our Debugging runbook:
Debugging runbook
Steps to debug common issues with the library.
我们很乐意为你解答任何问题。你可以通过多种方式联系我们或其他社区成员以获取帮助:
¥We are always happy to help you with any questions you might have. There are multiple ways you can reach out to us or other community members to get help:
请记住,总有一个人在你身后为你解决一个问题。请尽可能提供帮助。
¥And remember, there is always a person who’s one problem behind you. Be kind and offer help when you can.