生命周期事件

生命周期事件允许你订阅在请求/响应处理期间发生的内部库事件。在使用 MSW 进行开发或测试时,你不太可能直接使用此 API。但是,有许多用例可以使此 API 受益:

¥Life-cycle events allow you to subscribe to the internal library events occurring during the request/response handling. You are unlikely to use this API directly while developing or testing with MSW. There are, however, a number of use-cases when this API can be beneficial:

  • 当你构建封装 MSW 的第三方库时;

    ¥When you’re building a third-party library encapsulating MSW;

  • 当你希望透明地监​​视应用中的请求/响应时;

    ¥When you wish to transparently monitor requests/responses in your application;

  • 当你希望明确等待某个请求/响应时。

    ¥When you wish to explicitly wait for a certain request/response.

注意事项

¥Precautions

只读

¥Read-only

生命周期事件 API 是只读的。这意味着你可以观察请求和响应,但不能影响它们。如果你希望影响请求处理,请考虑改用 setupWorker 和/或 setupServer

¥The life-cycle events API is read-only. This means that you can observe requests and responses but cannot affect them. If you wish to affect the request handling, consider using setupWorker and/or setupServer instead.

阅读前克隆

¥Clone before reading

通过此 API 公开的 requestresponse 引用是发生的请求和收到的响应的精确 Fetch API 表示。如果你希望阅读它们的主体,请不要忘记克隆它们。

¥The request and response references exposed through this API are exact Fetch API representations of the occurred requests and received responses. If you wish to read their bodies, don’t forget to clone them.

server.events.on('request:start', async ({ request }) => {
  // Read the request body as text for every request
  // that occurs in your application.
  const payload = await request.clone().text()
})

用法

¥Usage

生命周期事件 API 在工作器/服务器实例上的 events 属性下公开:

¥The life-cycle events API is exposed under the events property on the worker/server instance:

// In the browser.
const worker = setupWorker(...handlers)
worker.events
 
// In Node.js.
const server = setupServer(...handlers)
server.events

API 的整体形状在环境之间是相同的。

¥The overall shape of the API is identical between the environments.

events 属性包含一个自定义事件触发器,该触发器有意限制为仅监听事件而不能发出它们(触发事件由库执行)。你可以在 events 对象上使用 addListener()once()removeListener() 等方法。

¥The events property contains a custom event emitter intentionally restricted to only listen to the events without the ability to emit them (emitting events is performed by the library). You can use methods like addListener(), once() and removeListener() on the events object.

// Observe any outgoing requests in your application.
server.events.on('request:start', ({ request, requestId }) => {
  console.log('Outgoing request:', request.method, request.url)
})

请求事件

¥Request events

request:start

每当你的应用中发生请求时,都会发出 request:start 事件。你可以在监听器的参数中访问 request 引用。

¥The request:start event is emitted whenever a request occurs in your application. You can access the request reference in the argument of the listener.

worker.events.on('request:start', ({ request, requestId }) => {
  console.log('Outgoing request:', request.method, request.url)
})

request:match

每当拦截的请求定义了相应的请求处理程序时,都会发出 request:match 事件。

¥The request:match event is emitted whenever an intercepted request has a corresponding request handler defined.

request:unhandled

当拦截的请求没有定义相应的请求处理程序时,就会发出 request:unhandled 事件,并将按原样执行。

¥The request:unhandled event is emitted whenever an intercepted request has no corresponding request handler defined and will be performed as-is.

request:end

每当请求结束时,都会发出 request:end 事件。无论是否处理了所有请求,都会发出此事件。

¥The request:end event is emitted whenever a request has ended. This event is emitted for all requests, regardless if they were handled or not.

响应事件

¥Response events

response:mocked

每当发送模拟响应时,都会发出 response:mocked 事件。你可以在此事件的监听器中访问 response 引用和相应的 request 引用。

¥The response:mocked event is emitted whenever a mocked response is sent. You can access both the response reference and the respective request reference in the listener to this event.

server.events.on('response:mocked', ({ request, requestId, response }) => {
  console.log(
    '%s %s received %s %s',
    request.method,
    request.url,
    response.status,
    response.statusText
  )
})

response:bypass

当发送原始(绕过)响应时,就会发出 response:bypass 事件。与 response:mocked 事件类似,你可以在监听器中访问 responserequest 引用。

¥The response:bypass event is emitted whenever an original (bypassed) response is sent. Similar to the response:mocked event, you can access the response and request references in the listener.

其他事件

¥Other events

unhandledException

当响应解析器函数中抛出未处理的错误时,就会发出 unhandledException 事件。你可以在此事件的监听器中访问相关的 requestrequestId,以及抛出的 error 引用。

¥The unhandledException event is emitted whenever an unhandled error is thrown within the response resolver function. You can access the relevant request and requestId in the listener to this event, as well as the thrown error reference.

server.events.on('unhandledException', ({ request, requestId, error }) => {
  console.log('%s %s errored! See details below.', request.method, request.url)
  console.error(error)
})

删除监听器

¥Removing listeners

removeListener()

  • name,字符串,要删除的事件名称。

    ¥name, String, the event name to remove.

  • listener,函数,要删除的事件监听器。

    ¥listener, Function, the event listener to remove.

server.events.removeListener('request:start', requestStartListener)

removeAllListeners()

  • name,字符串(可选),要删除的事件名称。

    ¥name, String (Optional), the event name to remove.

当不带任何参数调用时,.removeAllListeners() 将删除附加到当前 worker/server 实例的所有事件:

¥When called without any arguments, .removeAllListeners() removes all events attached to the current worker/server instance:

server.events.removeAllListeners()

你可以提供 name 参数以仅删除相应事件的监听器:

¥You can provide a name argument to only remove the listeners for the respective event:

server.events.removeAllListeners('request:start')