Node.js 集成

在 Node.js 中设置 Mock Service Worker。

在 Node.js 中,MSW 通过修补原生请求发出模块(如 httphttps)来启用 API 模拟,这使其能够观察和影响当前进程的传出流量。

¥In Node.js, MSW enables API mocking by patching native request-issuing modules, like http and https, which gives it the means to observe and affect the outgoing traffic for the current process.



msw/node 导入 setupServer 函数并调用它,提供你的请求处理程序作为参数。

¥Import the setupServer function from msw/node and call it, providing your request handlers as the argument.

// src/mocks/node.js
import { setupServer } from 'msw/node'
import { handlers } from './handlers'
export const server = setupServer(...handlers)

然后,你使用返回的 server 对象来控制当前 Node.js 进程中的 API 模拟。

¥You then use the returned server object to control API mocking in the current Node.js process.

了解有关 setupServer API 的更多信息。

¥Learn more about the setupServer API.


¥Enable mocking

Node.js 应用

¥Node.js application

在你的 Node.js 应用中的任何位置导入 server 并调用 .listen() 方法以启用 API 模拟。我们建议将此作为应用入口模块中的第一件事,以便 MSW 尽早影响所有请求。

¥Import the server anywhere in your Node.js application and call the .listen() method to enable API mocking. We recommend doing this as the first thing in your application’s entry module so MSW would affect all the requests early on.

// src/index.js
import { server } from './mocks/node'
// ...the rest of your Node.js application.

server.listen() 是一个同步 API,因此你不必等待它。

¥server.listen() is a synchronous API so you don’t have to await it.


¥Test runner

Node.js 中 MSW 的最常见用途之一是与 Jest 或 Vitest 等测试运行器一起使用。虽然 Node.js 中 MSW 的一般原则仍然适用于此,但测试运行器公开了一个方便的设置 API,以便在测试运行的正确阶段启用模拟。

¥One of the most common uses of MSW in Node.js is with test runners like Jest or Vitest. While the general principles of MSW in Node.js still apply there, the test runners expose a convenient setup API to enable mocking in the right phases of the test run.

将 MSW 与任何测试运行器集成有三个关键步骤:

¥There are three key steps to integrating MSW with any test runner:

  1. 在运行所有测试之前启用模拟(server.listen());

    ¥Enable mocking before all tests run (server.listen());

  2. 在测试之间重置任何请求处理程序(server.resetHandlers());

    ¥Reset any request handlers between tests (server.resetHandlers());

  3. 在所有测试运行后恢复原生请求发出模块(server.close())。

    ¥Restore native request-issuing modules after all tests run (server.close()).

例如,你可以这样在 Vitest 中设置 MSW,使用其 beforeAllafterEachafterAll 钩子:

¥For example, this is how you would set up MSW in Vitest, using its beforeAll, afterEach, and afterAll hooks:

// vitest.setup.js
import { beforeAll, afterEach, afterAll } from 'vitest'
import { server } from './src/mocks/node'
beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())



要确认设置成功,请在 server 对象上创建一个简单的传出请求监听器:

¥To confirm a successful setup, create a simple outgoing request listener on the server object:'request:start', ({ request }) => {
  console.log('MSW intercepted:', request.method, request.url)

你刚才使用的函数称为 生命周期事件,它们是观察网络流量而不影响网络流量的强大工具。

¥What you’ve used just now is called Life-cycle events, and they are a powerful tool to observe the network traffic without affecting it.

获取执行任何 HTTP 请求的应用的状态,并确认你可以在终端中看到打印的控制台消息。

¥Get to the state of your application that performs any HTTP requests and confirm you can see that console message printed in your terminal.


¥Related materials