- Introduction
- Getting started
- Philosophy
- Comparison
- Limitations
- Debugging runbook
- FAQ
- Basics
- Concepts
- Network behavior
- Integrations
- API
- CLI
- Best practices
- Recipes
- Cookies
- Query parameters
- Response patching
- Polling
- Streaming
- Network errors
- File uploads
- Responding with binary
- Custom worker script location
- Global response delay
- GraphQL query batching
- Higher-order resolver
- Keeping mocks in sync
- Merging Service Workers
- Mock GraphQL schema
- Remote Request Interception
- Using CDN
- Using custom "homepage" property
- Using local HTTPS
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 name | Description |
---|---|
"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) {
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()
},
})