快速入门
在五分钟内启动并运行 MSW。
本指南将指导你完成 MSW 的基本设置,以便在 Node.js 测试中使用 Vitest 拦截 HTTP 请求。
¥This guide will take you through the barebones setup of MSW for intercepting HTTP requests in your Node.js tests with Vitest.
1. 安装
¥ Installation
npm i msw --save-dev
2. 请求处理程序
¥ Request handlers
从 msw
包中导入 http
命名空间并创建你的第一个请求处理程序。这些函数负责拦截请求并处理其响应。
¥Import the http
namespace from the msw
package and create your first request handler. Those are functions responsible for intercepting requests and handling their responses.
让我们为 GET https://api.example.com/user
请求定义一个请求处理程序:
¥Let’s define a request handler for a GET https://api.example.com/user
request:
// src/mocks/handlers.ts
import { http, HttpResponse } from 'msw'
export const handlers = [
http.get('https://api.example.com/user', () => {
return HttpResponse.json({
id: 'abc-123',
firstName: 'John',
lastName: 'Maverick',
})
}),
]
MSW 支持拦截 HTTP、GraphQL 和 WebSocket API。
¥MSW supports intercepting both HTTP, GraphQL, and WebSocket APIs.
3. 流程级集成
¥ Process-level integration
MSW 的核心优势之一是能够在不同的工具和环境中重用相同的模拟(例如 handlers.ts
)。请求处理程序本身不执行任何操作。必须将它们分别提供给 setupServer
或 setupWorker
函数,以在 Node.js 或浏览器进程中配置 API 模拟。
¥One of the core benefits of MSW is the ability to reuse the same mocks (e.g. handlers.ts
) across different tools and environments. On their own, request handlers don’t do anything. They have to be provided to the setupServer
or setupWorker
functions to configure API mocking in a Node.js or a browser process, respectively.
由于 Vitest 测试在 Node.js 进程中运行,因此我们使用 msw/node
中的 setupServer
并创建一个 node.ts
集成点:
¥Since Vitest tests run in a Node.js process, let’s use setupServer
from msw/node
and create a node.ts
integration point:
// src/mocks/node.ts
import { setupServer } from 'msw/node'
import { handlers } from './handlers.js'
export const server = setupServer(...handlers)
此集成与 Vitest 无关。你可以重用它将 MSW 应用于任何 Node.js 进程。
¥This integration has nothing specific to Vitest. You can reuse it to apply MSW to any Node.js process.
4. 工具级集成
¥ Tool-level integration
在此步骤中,你将找到在 Node.js 进程中启用 API mocking 的适当位置。对于 Vitest 来说,这个位置是测试设置文件,它会在测试之前运行。打开该文件(或创建该文件)并调用 server.listen()
启用模拟,如下所示:
¥At this step, you find the appropriate place to enable API mocking in your Node.js process. In the case of Vitest, that place is the test setup file, which runs before your tests. Open that file (or create it) and call server.listen()
in enable mocking as follows:
// vitest.setup.ts
import { beforeAll, afterEach, afterAll } from 'vitest'
import { server } from './mocks/node.js'
beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())
确保你的
vitest.config.ts
中的test.setupFiles
数组中列出了vitest.setup.ts
模块。¥Make sure you have the
vitest.setup.ts
module listed in thetest.setupFiles
array in yourvitest.config.ts
.
5. 运行测试
¥ Run tests
一旦 MSW 集成到你的 Vitest 设置中,它将按照处理程序中的定义控制网络。
¥Once MSW is integrated into your Vitest setup, it will control the network as defined in your handlers.
// test/example.test.ts
// @vitest-environment node
import { test, expect } from 'vitest'
test('responds with the user', async () => {
const response = await fetch('https://api.example.com/user')
await expect(response.json()).resolves.toEqual({
id: 'abc-123',
firstName: 'John',
lastName: 'Maverick',
})
})
npx vitest
✓ test/example.test.ts (1 test) 1ms
✓ responds with the user 0ms
Test Files 1 passed (1)
Tests 1 passed (1)
Start at 12:15:23
Duration 166ms (transform 19ms, setup 0ms, collect 7ms, tests 1ms, environment 0ms, prepare 43ms)
使用示例
¥Usage examples
MSW 应用于环境级别(Node.js 或浏览器)。将其与不同的工具集成将归结为找到该工具提供给你的适当环境入口点,并遵循与上面相同的设置。
¥MSW applies on the environment level (Node.js or browser). Integrating it with different tools will come down to finding the appropriate environment entrypoint provided to you by that tool and following the same setup as you did above.
作为参考,我们准备了一系列精选的使用示例:
¥For reference, we’ve prepared a curated collection of usage examples:
Usage examples
Examples of Mock Service Worker usage with various frameworks and libraries.
后续步骤
¥Next steps
本指南是一个很好的起点,但你可以使用该库做更多的事情。我们强烈建议你阅读此文档,以了解有关 MSW 功能的更多信息。以下是一些值得关注的精彩主题:
¥This guide is a good starting point but you can do so much more with the library. We highly encourage you to explore this documentation to learn more about the capabilities of MSW. Here are some great topics to follow up on:
Browser integration
Set up Mock Service Worker in the browser.
Default behaviors
Important default behaviors of Mock Service Worker.
Intercepting requests
Learn how to intercept outgoing requests.
Best practices
Tips & tricks for getting the most out of Mock Service Worker.
需要帮助吗?
¥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.