setupWorker

在浏览器中配置请求拦截。

setupWorker() 函数准备客户端-工作者通信通道以在浏览器中启用 API 模拟。

¥The setupWorker() function prepares the client-worker communication channel to enable API mocking in the browser.

调用签名

¥Call signature

setupWorker() 函数需要一个可选的 请求处理程序 列表作为其参数并返回一个 Worker 实例

¥The setupWorker() function expects an optional list of Request handlers spread as its arguments and returns a Worker instance.

当不带任何参数调用时,该函数将返回一个没有网络描述(即没有请求处理程序)的工作器实例。使用 worker.use()worker.resetHandlers() 等方法向工作器实例添加和删除运行时请求处理程序。

¥When called without any arguments, the function will return you a worker instance that has no network description (i.e. no request handlers). Use the methods like worker.use() and worker.resetHandlers() to add and remove runtime request handlers to the worker instance.

import { setupWorker } from 'msw/browser'
 
const worker = setupWorker()
// worker.start()
// worker.use(...handlers)

但是,如果你将请求处理程序作为 setupWorker() 函数的传播参数提供,则这些处理程序将被视为初始的,并且即使在重置处理程序时也将始终保留在工作实例上(了解如何退出此 此处)。

¥However, if you provide request handlers as the spread argument to the setupWorker() function, those handlers will be considered initial and will always persist on the worker instance even when resetting the handlers (learn how to opt-out from this here).

import { http, HttpResponse } from 'msw'
import { setupWorker } from 'msw/browser'
 
const worker = setupWorker(
  http.get('/resource', () => HttpResponse.json({ id: 'abc-123' }))
)

Worker 实例

¥Worker instance

setupWorker() 函数返回一个工作者实例,它是一个对象,你可以使用它来控制当前浏览器环境中的 API 模拟。下面,你可以看到工作实例上可用的方法列表。

¥The setupWorker() function returns you a worker instance that is an object you can use to control API mocking in the current browser environment. Below, you can see the list of methods available on the worker instance.

方法

¥Methods