listen()

启用当前进程中的请求拦截。

调用签名

¥Call signature

function listen(options?: ListenOptions): void

用法

¥Usage

通常在测试框架的 beforeAll 钩子中启用拦截。下面你可以找到一个使用 Jest 执行此操作的示例。

¥It’s common to enable the interception in the beforeAll hook of your testing framework. Below you can find an example of how to do that with Jest.

import { setupServer } from 'msw/node'
import { handlers } from './handlers'
 
const server = setupServer(...handlers)
 
beforeAll(() => {
  server.listen()
})

worker.start() 不同,.listen() 方法是同步的,因为没有要注册的工作程序或要建立的实际连接。

¥Unlike worker.start(), the .listen() method is synchronous because there are no workers to register or actual connections to establish.

选项

¥Options

onUnhandledRequest

  • 预定义策略或自定义策略(默认值:"warn")。

    ¥Predefined strategy or Custom strategy (default: "warn").

指定如何对任何请求处理程序未处理的请求做出反应。

¥Specifies how to react to requests that are not handled by any request handlers.

预定义策略

¥Predefined strategies

策略名称描述
"warn"(默认)打印警告但按原样执行请求。
"error"打印错误并停止请求执行。
"bypass"不打印任何内容并按原样执行请求。
server.listen({
  onUnhandledRequest: 'error',
})

自定义策略

¥Custom strategy

server.listen({
  onUnhandledRequest(request) {
    console.log('Unhandled %s %s', request.method, request.url)
  },
})

预定义策略可用作自定义回调的第二个参数,因此你可以重复使用它们。下面是一个示例,说明如何利用它来绕过静态资源,但仍对其他未处理的请求发出警告:

¥The pre-defined strategies are available as the second argument of the custom callback so you could reuse them. Here’s an example of how you can utilize that to bypass static assets but still warn on other unhandled requests:

server.listen({
  onUnhandledRequest(request, print) {
    const url = new URL(request.url)
 
    // Ignore requests to fetch static assets.
    if (url.pathname.includes('/assets/')) {
      return
    }
 
    // Otherwise, print a warning for any unhandled request.
    print.warning()
  },
})

默认情况下,MSW 会忽略通用静态资源请求,因此它们不会被视为未处理。如果你为 onUnhandledRequest 函数提供自定义回调,你将退出该行为。你可以随时通过手动调用 isCommonAssetRequest() 函数来使用它。

¥By default, MSW will ignore common static asset requests so they won’t be considered unhandled. If you provide a custom callback to the onUnhandledRequest function, you will opt out from that behavior. You can tap into it at any time by manually calling the isCommonAssetRequest() function.