LOGOMock Service Worker

listen()

Establishes a request interception instance previously configured via setupServer.

Options

onUnhandledRequest

  • "bypass" | "warn" | "error" | (req: MockedRequest) => void
  • (default: "warn")

Specifies how to handle a request that is not listed in the request handlers.

Pre-defined behaviors

Option nameDescription
"bypass"Performs an unhandled request as-is.
"warn"Prints a warning into stdout of the current process.
"error"Prints an error into stderr of the current process.
1const server = setupServer(
2 rest.get('/books', (req, res, ctx) => {
3 return res(ctx.json({ title: 'The Lord of the Rings' }))
4 }),
5)
6
7server.listen({
8 onUnhandledRequest: 'warn',
9})

Custom callback

When passed a function as a value of this option, the library executes that function whenever an unhandled request occurs. The behavior of such unhandled request won't be affected, but can be prevented if the custom callback function throws an exception.

1const server = setupServer(
2 rest.get('/books', (req, res, ctx) => {
3 return res(ctx.json({ title: 'The Lord of the Rings' }))
4 }),
5)
6
7server.listen({
8 onUnhandledRequest(req) {
9 console.error(
10 'Found an unhandled %s request to %s',
11 req.method,
12 req.url.href,
13 )
14 },
15})

Examples

In typical a testing setup you call .listen() in a setup hook before all your tests, making sure the request interception is at place once the test suits run.

Here's an example of using .listen() with Jest's beforeAll hook:

1import { setupServer } from 'msw/node'
2
3const server = setupServer(/* request handlers */)
4
5beforeAll(() => {
6 server.listen()
7})

Unlike a similar method on actual servers, .listen() operates synchronously, because there is no servers and, thus, no actual connection to establish.