listen()

Enable the interception of requests in the current process.

Call signature

function listen(options?: ListenOptions): void

Usage

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()
})

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

Options

onUnhandledRequest

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

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

Predefined strategies

Strategy nameDescription
"warn" (Default)Print a warning but perform the request as-is.
"error"Print an error and halt request execution.
"bypass"Does not print anything and perform the request as-is.
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) {
    // Ignore requests to fetch static assets.
    if (request.url.pathname.includes('/assets/')) {
      return
    }
 
    // Otherwise, print a warning for any unhandled request.
    print.warning()
  },
})