### Setup Server with Request Handlers Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/setup-server/index.mdx Import `setupServer` from `msw/node` and provide it with request handlers. Call `server.listen()` to start request interception. ```javascript import { http, HttpResponse } from 'msw' import { setupServer } from 'msw/node' // Provide the server-side API with the request handlers. const server = setupServer( http.get('/user', () => { return HttpResponse.json({ id: '15d42a4d-1948-4de4-ba78-b8a893feaf45', firstName: 'John', }) }) ) // Start the interception. server.listen() ``` -------------------------------- ### Jest Testing Setup with setupServer Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/setup-server/index.mdx Integrate `setupServer` into your Jest testing setup. Use `beforeAll` to start interception, `afterEach` to reset handlers, and `afterAll` to close the server. ```javascript // jest.setup.js import { setupServer } from 'msw/node' import { handlers } from './handlers' const server = setupServer(...handlers) beforeAll(() => { // Start the interception. server.listen() }) afterEach(() => { // Remove any handlers you may have added // in individual tests (runtime handlers). server.resetHandlers() }) afterAll(() => { // Disable request interception and clean up. server.close() }) ``` -------------------------------- ### Basic MSW Request Handler Example Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/blog/introducing-source.mdx Illustrates a simple HTTP GET request handler for the '/user' endpoint, returning a JSON response. ```javascript http.get('/user', () => { return Response.json({ login: 'kettanaito' }) }) ``` -------------------------------- ### Install MSW for development Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/quick-start.mdx Install Mock Service Worker as a development dependency using npm. ```bash npm i msw --save-dev ``` -------------------------------- ### Setup MSW server for Node.js Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/quick-start.mdx Configure the `setupServer` from `msw/node` to create an integration point for MSW in a Node.js environment. ```typescript // src/mocks/node.ts import { setupServer } from 'msw/node' import { handlers } from './handlers.js' export const server = setupServer(...handlers) ``` -------------------------------- ### Install MSW Latest Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/migrations/1.x-to-2.x.mdx Update your project to the latest version of Mock Service Worker. ```bash npm install msw@latest ``` -------------------------------- ### Install Latest MSW Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/blog/server-sent-events-are-here.mdx Install the latest version of MSW to utilize the new Server-Sent Events mocking features. ```sh npm i msw@latest ``` -------------------------------- ### Define Mocked Route with Mirage Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/comparison.mdx Mirage uses a `createServer` function with a `routes` method to define mock server routes. This example defines a GET route for '/movies'. ```javascript createServer({ routes() { this.get('/movies', () => { return ['Interstellar', 'Inception', 'Dunkirk'] }) }, }) ``` -------------------------------- ### Setup Server Instance in Node.js Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/integrations/node.mdx Import `setupServer` from `msw/node` and initialize it with your request handlers. This creates a server instance to control mocking in the current Node.js process. ```javascript import { setupServer } from 'msw/node' import { handlers } from './handlers' export const server = setupServer(...handlers) ``` -------------------------------- ### Install MSW Source Source: https://github.com/mswjs/mswjs.io/blob/main/websites/source.mswjs.io/src/content/docs/getting-started.mdx Add `@msw/source` and `msw` as development dependencies to your project. MSW Source requires `msw` to function. ```sh npm i msw @msw/source --save-dev ``` -------------------------------- ### start() Options Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/setup-worker/start.mdx Configuration options for the `worker.start()` method to customize Service Worker registration and request interception behavior. ```APIDOC ## Options ### `serviceWorker` #### `url` - _String_, default: `"/mockServiceWorker.js"` Custom Service Worker registration URL. Use this option if you are serving the worker script under a custom path. ```js worker.start({ serviceWorker: { url: '/assets/mockServiceWorker.js', }, }) ``` Keep in mind that a Service Worker can only control the network from the clients (pages) hosted at its level or down. You likely always want to register the worker at the root. #### `options` - [_Service Worker registration options_](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register#parameters) These options modify the Service Worker registration itself and are not related to MSW directly. ```js worker.start({ serviceWorker: { options: { // Narrow down the scope of the pages that the worker can control. scope: '/product', }, }, }) ``` ### `findWorker` - _Function_, expected return type: _Boolean_ A custom function to locate the worker script on the server. You may want to use this option if your application runs behind a proxy or has a dynamic hostname that otherwise prevents the library from locating the worker script at `/mockServiceWorker.js`. ```js worker.start({ findWorker(scriptUrl, mockServiceWorkerUrl) { return scriptUrl.includes('mockServiceWorker') }, }) ``` ### `quiet` - _Boolean_, default: `false` Disables all the logging from the library (e.g. the activation message, the intercepted requests' messages). ```js worker.start({ quiet: true, }) ``` ### `onUnhandledRequest` - _String_, default: `"warn"` - _Function_ Decide how to react to unhandled requests (i.e. those that do not have a matching request handler). #### Predefined strategies | Handling mode | Description | | ---------------- | ------------------------------------------------------------------------------ | | `warn` (Default) | Prints a warning message to the browser's console, performs the request as-is. | | `error` | Throws an error, aborts the request. | | `bypass` | Prints nothing, performs the request as-is. | #### Custom strategy ```js worker.start({ onUnhandledRequest(request, print) { // Ignore any requests containing "cdn.com" in their URL. if (request.url.includes('cdn.com')) { return } // Otherwise, print an unhandled request warning. print.warning() }, }) ``` > 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()`](/docs/api/is-common-asset-request) function. ### `waitUntilReady` - _Boolean_, default: `true` Defers any application requests that happen during the Service Worker registration. > Disabling this option is **not recommended** as this will create a race condition between the worker registration and your application's runtime. ``` -------------------------------- ### Integrate MSW with Vitest setup Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/quick-start.mdx Enable API mocking in Vitest by calling `server.listen()` in the test setup file. Ensure handlers are reset after each test and the server is closed after all tests. ```typescript // vitest.setup.ts import { beforeAll, afterEach, afterAll } from 'vitest' import { server } from './mocks/node.js' beforeAll(() => server.listen()) afterEach(() => server.resetHandlers()) afterAll(() => server.close()) ``` -------------------------------- ### Setup Node.js Server for Mocking Source: https://github.com/mswjs/mswjs.io/blob/main/websites/source.mswjs.io/src/content/docs/getting-started.mdx Integrate MSW into a Node.js process by setting up the server with your request handlers. Ensure handlers are imported correctly. Call `server.listen()` to activate the mocking. ```javascript import { setupServer } from 'msw/node' import { handlers } from './handlers' const server = setupServer(...handlers) server.listen() ``` -------------------------------- ### Setup Worker in Browser Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/integrations/browser.mdx Import `setupWorker` and your handlers to create a worker instance for browser environments. Learn about the `setupWorker` API. ```js // src/mocks/browser.js import { setupWorker } from 'msw/browser' import { handlers } from './handlers' export const worker = setupWorker(...handlers) ``` -------------------------------- ### Setup Mock Server for React Native Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/integrations/react-native.mdx Configure the mock server using `setupServer` from `msw/native`. This function takes your request handlers as arguments and is the same API as used in Node.js. ```js // src/mocks/server.js import { setupServer } from 'msw/native' import { handlers } from './handlers' export const server = setupServer(...handlers) ``` -------------------------------- ### Setup Server with Boundary Callback Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/blog/introducing-server-boundary.mdx Use `server.boundary()` to wrap a callback function. Any network behavior changes within this callback are isolated to its scope. ```javascript const server = setupServer() const boundCallback = server.boundary(callback) ``` -------------------------------- ### Example URL for Error Scenario Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/best-practices/dynamic-mock-scenarios.mdx Navigate to a URL with the `scenario` query parameter set to `error` to activate the error mock scenario. ```txt /?scenario=error/ http://localhost:3000/dashboard?scenario=error ``` -------------------------------- ### Setup Server and Listen Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/setup-server/listen.mdx Enable request interception in the `beforeAll` hook of your testing framework. This is a common pattern for setting up MSW in Node.js tests. ```javascript import { setupServer } from 'msw/node' import { handlers } from './handlers' const server = setupServer(...handlers) beforeAll(() => { server.listen() }) ``` -------------------------------- ### Install React Native Polyfills Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/integrations/react-native.mdx Install the necessary polyfills for MSW to function correctly in React Native. These include 'react-native-url-polyfill' and 'fast-text-encoding'. ```sh npm install react-native-url-polyfill fast-text-encoding ``` -------------------------------- ### Browser Setup for XMLHttpRequest Interceptor Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/recipes/xmlhttprequest-progress-events.mdx Import the XMLHttpRequest interceptor setup in your browser entry point. This ensures that the interceptor is applied before other MSW browser setup. ```typescript import './xhr' // The rest of your browser setup for MSW here. // (e.g. `setupWorker`, `handlers`, etc.) ``` -------------------------------- ### Install jest-fixed-jsdom Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/shared/jest-missing-globals.mdx Install the `jest-fixed-jsdom` package using npm to resolve missing Node.js globals. ```sh npm i jest-fixed-jsdom ``` -------------------------------- ### Import GraphQL Namespace Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/graphql/index.mdx Import the `graphql` namespace from MSW to start mocking GraphQL operations. ```typescript import { graphql } from 'msw' ``` -------------------------------- ### Log Request Start Event Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/life-cycle-events.mdx Subscribe to the `request:start` event on the worker to log details about outgoing requests in the browser. ```javascript worker.events.on('request:start', ({ request, requestId }) => { console.log('Outgoing request:', request.method, request.url) }) ``` -------------------------------- ### request:start event Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/life-cycle-events.mdx Emitted when a request occurs. Provides access to the `request` and `requestId`. ```APIDOC ## `request:start` event 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. ```js worker.events.on('request:start', ({ request, requestId }) => { console.log('Outgoing request:', request.method, request.url) }) ``` ``` -------------------------------- ### Create a Server Boundary with Initial Handlers Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/setup-server/boundary.mdx When creating a server boundary, it inherits the request handlers from the scope it's defined in. This example shows a boundary that uses the initial handlers provided to `setupServer`. ```javascript const server = setupServer( http.get('https://example.com/user', () => { return HttpResponse.json({ name: 'John' }) }) ) server.boundary(async () => { // The user request will return a 200 JSON response // as described in the initial request handlers // provided to the "setupServer" call above. await fetch('https://example.com/user') })() ``` -------------------------------- ### Nested Server Boundary Example Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/blog/introducing-server-boundary.mdx Demonstrates how nested server boundaries inherit and manage request handler states, including the effect of server.resetHandlers(). ```javascript const server = setupServer(A) server.boundary(() => { server.use(B) // Initial handlers: [A] // Runtime handler: [B] // Current handlers: [A, B] server.boundary(() => { server.use(C) // Initial handlers: [A, B] // Runtime handlers: [C] // Current handlers: [A, B, C] server.resetHandlers() // Runtime handlers: [] // Current handlers: [A, B] })() })() ``` -------------------------------- ### Simulate Client Sending Message Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/websocket/client-events/index.mdx Example of a client sending a message ('hello world') after its WebSocket connection is opened. This demonstrates the client-side action that triggers the 'message' event interception. ```js // app.js const ws = new WebSocket(url) ws.onopen = () => { ws.send('hello world') // "Client sent data: hello world" } ``` -------------------------------- ### GraphQL Batched Query Example (Apollo) Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/graphql/mocking-responses/query-batching.mdx An example of a batched GraphQL query structure used by Apollo, grouping multiple queries into a single array. ```graphql [ query GetUser { user { id } }, query GetProduct { product { name } } ] ``` -------------------------------- ### Example Batched GraphQL Query Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/graphql/mocking-responses/query-batching.mdx A GraphQL query demonstrating batching by using field aliases for multiple operations. ```graphql query { user_0: user { id } product_0: product { name } } ``` -------------------------------- ### Importing the SSE namespace Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/sse/index.mdx Import the `sse` namespace from the 'msw' library to start mocking Server-Sent Events. ```ts import { sse } from 'msw' ``` -------------------------------- ### Log Outgoing Request Details Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/life-cycle-events.mdx Use the `request:start` event to log details about outgoing requests, such as their method and URL. ```javascript // Observe any outgoing requests in your application. server.events.on('request:start', ({ request, requestId }) => { console.log('Outgoing request:', request.method, request.url) }) ``` -------------------------------- ### Vitest test execution output Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/quick-start.mdx Example output from running Vitest tests, indicating successful execution and timing. ```bash ✓ test/example.test.ts (1 test) 1ms ✓ responds with the user 0ms Test Files 1 passed (1) Tests 1 passed (1) Start at 12:15:23 Duration 166ms (transform 19ms, setup 0ms, collect 7ms, tests 1ms, environment 0ms, prepare 43ms) ``` -------------------------------- ### Replay sequential responses from HAR Source: https://github.com/mswjs/mswjs.io/blob/main/websites/source.mswjs.io/src/content/docs/integrations/har.mdx Example of setting up MSW server with handlers generated from HAR and making sequential requests to observe the replayed responses. ```javascript const handlers = fromTraffic(traffic) setupServer(...handlers).listen() await fetch('https://example.com/cart').then((res) => res.json()) // {"items":[]} await fetch('https://example.com/cart').then((res) => res.json()) // {"items":[{"id":"abc-123"}]} ``` -------------------------------- ### Listen with Custom Strategy Using Predefined Handler Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/setup-server/listen.mdx Implement a custom strategy for unhandled requests that reuses predefined behaviors like warning or bypassing. This example bypasses static assets but warns on other unhandled requests. ```javascript 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() }, }) ``` -------------------------------- ### Astro Project Commands Source: https://github.com/mswjs/mswjs.io/blob/main/websites/source.mswjs.io/README.md Common commands for managing your Astro project, including installation, development, building, and previewing. ```sh npm install ``` ```sh npm run dev ``` ```sh npm run build ``` ```sh npm run preview ``` ```sh npm run astro ... ``` ```sh npm run astro -- --help ``` -------------------------------- ### Example `Service-Worker-Allowed` header in request Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/recipes/custom-worker-script-location.mdx Demonstrates the `Service-Worker-Allowed` header being sent in a request for the Service Worker script. This header is crucial for extending the worker's scope. ```txt GET /assets/mockServiceWorker.js HTTP/1.0 content-type: application/javascript; charset=utf-8; service-worker-allowed: / ``` -------------------------------- ### Check MSW Package Version Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/runbook.mdx Compare the installed `msw` package version with the latest published version to identify potential upgrade needs. ```sh npm ls msw ``` ```sh npm view msw version ``` -------------------------------- ### Usage Example: Response Patching Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/bypass.mdx Demonstrates how to use `bypass` within a request handler to fetch the original resource and then patch its response. ```APIDOC ## Usage This method is designed to perform HTTP requests outside of the library's interception algorithm. Requests performed via `bypass()` _will never be intercepted_, even if there are otherwise matching request handlers present in the network description. This special behavior enables more complex network scenarios, such as [Response patching](/docs/http/mocking-responses/response-patching): ```js /bypass/1,3 {7} import { http, bypass, HttpResponse } from 'msw' export const handlers = [ http.get('/user', async ({ request }) => { // Perform the intercepted "GET /user" request as-is // by passing its "request" reference to the "bypass" function. const response = await fetch(bypass(request)) const realUser = await response.json() // Return a mocked JSON response by patching the original response // together with a mocked data. return HttpResponse.json({ ...realUser, lastName: 'Maverick', }) }), ] ``` ``` -------------------------------- ### Add Dummy Fetch Call Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/runbook.mdx If your application only makes one request, add a dummy fetch call after MSW setup to ensure the worker is active and intercepting requests. ```js fetch('https://example.com') ``` -------------------------------- ### Basic GET Request Handler Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/http/intercepting-requests/index.mdx Intercepts GET requests to '/resource' and logs request details. This is a fundamental example of defining a request handler. ```typescript http.get('/resource', ({ request }) => { console.log(request.method, request.url) }) ``` -------------------------------- ### Define Mocked Response with JSON Server Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/comparison.mdx JSON Server uses a resource-first format to implicitly generate request paths and mock responses. This example shows a JSON structure that defines posts. ```json { "posts": [ { "id": 1, "title": "json-server" }, { "id": 2, "title": "mock-service-worker" } ] } ``` -------------------------------- ### Start the worker with a custom service worker URL Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/setup-worker/start.mdx Use the `serviceWorker.url` option to specify a custom path for the Service Worker script if it's not served from the root. ```javascript worker.start({ serviceWorker: { url: '/assets/mockServiceWorker.js', }, }) ``` -------------------------------- ### Invalid GET Request Example Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/blog/why-use-mock-service-worker.mdx Illustrates how stubbing `window.fetch` can mask errors, such as sending a body with a GET request, which would normally crash the application but goes unnoticed with a stubbed client. ```js // Here I'm constructing a GET request with a body. fetch('/resource', { body: 'Hello world' }) ``` -------------------------------- ### Create Astro Project with Basics Template Source: https://github.com/mswjs/mswjs.io/blob/main/websites/source.mswjs.io/README.md Use this command to initialize a new Astro project with the 'Basics' template. ```sh npm create astro@latest -- --template basics ``` -------------------------------- ### Handling PATCH requests with path parameters Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/http.mdx Use `http.patch` to intercept PATCH requests. This example demonstrates accessing multiple path parameters. ```javascript http.patch('/cart/:cartId/order/:orderId', async ({ request, params }) => { const { cartId, orderId } = params const orderUpdates = await request.json() console.log( 'Updating order "%s" in cart "%s":', orderId, cartId, orderUpdates, ) }) ``` -------------------------------- ### Add Request Start Listener Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/runbook.mdx Add a `request:start` life-cycle event listener to your `worker` or `server` instance to log all outgoing requests intercepted by MSW. This helps verify MSW setup and identify if requests are being intercepted. ```js server.events.on('request:start', ({ request }) => { console.log('Outgoing:', request.method, request.url) }) ``` -------------------------------- ### Declare Mock Response with Response Class in MSW 2.x Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/migrations/1.x-to-2.x.mdx MSW 2.x requires you to return a standard `Response` instance. This example shows how to create a JSON response. ```javascript import { http } from 'msw' http.get('/resource', () => { return new Response(JSON.stringify({ id: 'abc-123' }), { headers: { 'Content-Type': 'application/json', }, }) }) ``` -------------------------------- ### Polling Request/Response Sequence Example Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/http/mocking-responses/polling.mdx Illustrates the sequence of requests and responses when using the polling handler. The 'degree' value increases with each request until it reaches its final state. ```json GET /weather/london // { "degree": 26 } GET /weather/london // { "degree": 27 } GET /weather/london // { "degree": 28 } // All subsequent requests will respond // with the latest returned response. GET /weather/london // { "degree": 28 } ``` -------------------------------- ### Prepend Request Handlers with setupServer Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/setup-server/use.mdx Use the `server.use()` method to add request handlers to a server instance. This is useful for dynamically adding handlers after the server has been initially set up. ```javascript import { http } from 'msw' import { setupServer } from 'msw/node' const server = setupServer() server.use(http.get('/resource', resolver), http.post('/resource', resolver)) ``` -------------------------------- ### Clear SWR Cache in Test Setup Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/runbook.mdx Example of clearing the SWR cache using `cache.clear()` in a `beforeEach` block. This prevents stale mock responses from affecting subsequent tests. ```typescript import { cache } from 'swr' beforeEach(() => { // Reset the cache before each new test so there are // no stale responses when requesting same endpoints. cache.clear() }) ``` -------------------------------- ### Using Custom SearchParamsHandler Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/request-handler.mdx Example of using the custom `SearchParamsHandler` to create a request handler that extracts and returns the 'id' from URL search parameters. This demonstrates how to integrate custom handlers into your MSW setup. ```javascript // handlers.js import { HttpResponse } from 'msw' import { SearchParamsHandler } from './SearchParamsHandler' export const handlers = [ new SearchParamsHandler({ id: 'abc-123' }, ({ request, searchParams }) => { // The custom request handler exposes the reference to // the "URLSearchParams" instance of the intercepted request // so we can operate with it directly in the resolver. const id = searchParams.get('id') return HttpResponse.json({ id }) }), ] ``` -------------------------------- ### Using `server.use()` Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/setup-server/use.mdx Demonstrates how to use the `server.use()` method to add request handlers to a server instance. You can prepend multiple handlers at once. ```APIDOC ## Call signature ```js import { http } from 'msw' import { setupServer } from 'msw/node' const server = setupServer() server.use(http.get('/resource', resolver), http.post('/resource', resolver)) ``` ### Description Prepends request handlers to the current server instance. The prepended request handlers persist on the server instance as long as the current Node.js runtime exists. ``` -------------------------------- ### Sending a File Upload Request with Fetch Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/http/mocking-responses/file-uploads.mdx Example of using the `fetch` API to send a file upload. Creates a `FormData` object, appends a `Blob` as a file, and sends a POST request to '/upload'. ```javascript const data = new FormData() const file = new Blob(['Hello', 'world'], { type: 'text/plain' }) data.set('file', file, 'doc.txt') fetch('/upload', { method: 'POST', body: data, }) ``` -------------------------------- ### MSW SetupServerApi Class Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/blog/introducing-server-boundary.mdx Illustrates the internal request handler management of MSW's SetupServerApi, showing how handlers are stored and modified. ```javascript class SetupServerApi { constructor(...initialHandlers) { this.initialHandlers = initialHandlers this.currentHandlers = [...this.initialHandlers] } use(...runtimeHandlers) { this.currentHandlers.unshift(...runtimeHandlers) } resetHandlers() { this.currentHandlers = [...this.initialHandlers] } } ``` -------------------------------- ### Define a GET request handler Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/quick-start.mdx Create a request handler for a specific GET endpoint that returns a JSON response. ```typescript // src/mocks/handlers.ts import { http, HttpResponse } from 'msw' export const handlers = [ http.get('https://api.example.com/user', () => { return HttpResponse.json({ id: 'abc-123', firstName: 'John', lastName: 'Maverick', }) }), ] ``` -------------------------------- ### OpenAPI JSON Schema Example Source: https://github.com/mswjs/mswjs.io/blob/main/websites/source.mswjs.io/src/content/docs/integrations/open-api.mdx An example of a JSON response generated from an OpenAPI schema with a 'uuid' format for the 'id' property. ```json { "id": "a5d43b08-2446-4da3-ab63-47e3dced6b0c" } ``` -------------------------------- ### GraphQL Mutation Example Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/graphql/intercepting-operations/mutations.mdx This is an example of a GraphQL mutation that can be intercepted by the MSW handler. It defines the mutation name and accepts variables. ```graphql mutation CreateUser($name: String!) { createUser(name: $name) { id name } } ``` -------------------------------- ### Intercepting a GET request Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/http.mdx Use `http.get` to intercept GET requests to a specific path. Access path parameters via the `params` object in the resolver. ```javascript http.get('/user/:id', ({ params }) => { const { id } = params console.log('Fetching user with ID "%s"', id) }) ``` -------------------------------- ### MSW WebSocket Type Error Example Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/websocket/type-safety.mdx This example demonstrates that MSW does not support type arguments for WebSocket event handlers, resulting in a type error. ```typescript import { ws } from 'msw' ws.link(url) // ^^^^^^^^^^^^ Type error! ``` -------------------------------- ### Concurrent Test Suite with MSW Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/blog/introducing-server-boundary.mdx Demonstrates a common test suite structure using `it.concurrent` and `setupServer` that can lead to race conditions due to shared global state. ```javascript import { http, HttpResponse } from 'msw' import { setupServer } from 'msw/node' const server = setupServer( // The request handlers provided to the "setupServer" // call are considered initial, or "happy path" handlers. http.get('https://example.com/user', () => { return HttpResponse.json({ name: 'John' }) }) ) beforeAll(() => server.listen()) afterAll(() => server.close() it.concurrent('fetches the user', async () => { // This test expects the outgoing requests to be // resolved against the initial request handlers. const user = await fetch('https://example.com/user').then(res => res.json()) expect(user).toEqual({ name: 'John' }) }) it.concurrent('handles requesting a non-existing user', async () => { // This test provides a request handler "override", // which makes all user requests result in a 404 Not Found response. server.use( http.get('https://example.com/user', () => { return new HttpResponse(null, { status: 404 }) }) ) }) it.concurrent('handles network errors', async () => { // And this test provides yet another override, // this time making all user requests produce a network error. server.use( http.get('https://example.com/user', () => { return HttpResponse.error() }) ) }) ``` -------------------------------- ### setupWorker() Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/setup-worker/index.mdx Initializes the Service Worker with optional request handlers. Returns a worker instance. ```APIDOC ## setupWorker() ### Description Configures the client-worker communication channel to enable API mocking in the browser. It accepts an optional list of request handlers and returns a Worker instance. ### Parameters #### Handlers - `...handlers` (Array) - Optional. A list of request handlers to be initially registered with the worker. ### Returns - `Worker` - An instance of the worker that can be used to control API mocking. ### Usage ```javascript import { setupWorker } from 'msw/browser' // With no initial handlers const worker = setupWorker() // With initial handlers const worker = setupWorker( http.get('/resource', () => HttpResponse.json({ id: 'abc-123' })) ) ``` -------------------------------- ### Define a REST API GET request handler with MSW Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/comparison.mdx Use `http.get` to define a handler for GET requests to a specific path. Return `HttpResponse.json` to mock a JSON response. ```javascript http.get('/movies', () => { return HttpResponse.json(['Interstellar', 'Inception', 'Dunkirk']) }) ``` -------------------------------- ### Worker Instance Methods Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/setup-worker/index.mdx Methods available on the worker instance returned by setupWorker. ```APIDOC ## Worker Instance Methods ### `start(options)` Starts the Service Worker. ### `stop()` Stops the Service Worker. ### `use(...handlers)` Adds new request handlers to the worker instance. ### `resetHandlers(...handlers)` Resets the worker's request handlers to a specified list, or to the initial handlers if none are provided. ### `restoreHandlers()` Restores the worker's request handlers to their initial state. ### `listHandlers()` Returns a list of all currently active request handlers on the worker. ``` -------------------------------- ### http.get() Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/http.mdx Intercepts GET requests to a specified endpoint. ```APIDOC ## GET /user/:id ### Description Intercepts GET requests to a specified endpoint. ### Method GET ### Endpoint /user/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user. ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **field1** (type) - Description ### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### CustomRequestHandler Class Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/request-handler.mdx Example of extending the RequestHandler class to create a custom handler. ```APIDOC ## Call signature ```js import { RequestHandler } from 'msw' export class CustomRequestHandler extends RequestHandler { constructor(args) { super(args) } } ``` The `RequestHandler` class constructor expects a single `args` object with the following properties: | Argument name | Type | Description | | ------------- | ---------- | -------------------------------------------------------------------------------------------------------------- | | `info` | `object` | Request handler [information](#info) object. | | `resolver` | `Function` | [Response resolver](/docs/http/intercepting-requests/#response-resolver) function to handle matching requests. | | `options` | `object` | _Optional_. Request handler [options](#request-handler-options). | ``` -------------------------------- ### Start the worker with default options Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/setup-worker/start.mdx Call `worker.start()` without arguments to register the Service Worker at `./mockServiceWorker.js` and begin request interception. Remember to await the promise it returns to ensure the worker is ready before making network requests. ```javascript import { setupWorker } from 'msw/browser' import { handlers } from './handlers' const worker = setupWorker(...handlers) await worker.start() // Promise<{ pending }> ``` -------------------------------- ### Connect to Server Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/sse.mdx Use `server.connect()` to establish the actual server connection for SSE. The returned `source` object can be used to listen to events. ```typescript const source = server.connect() ``` -------------------------------- ### Specify Public Directory for MSW Init Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/cli/init.mdx Provide the relative path to your application's public directory when initializing MSW. For Next.js, this is typically './public'. ```bash npx msw init ./public ``` -------------------------------- ### GraphQL Query Definition Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/graphql/intercepting-operations/queries.mdx This is an example of a GraphQL query that would be intercepted by the `ListUsers` handler. ```graphql query ListUsers { users { id name } } ``` -------------------------------- ### Filtering Handlers Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/setup-server/list-handlers.mdx Demonstrates how to filter the list of handlers, for example, to only include HTTP handlers. ```APIDOC ## Filtering Handlers ### Description Filter the list of handlers returned by `server.listHandlers()` using `instanceof` checks to select specific types of handlers (e.g., HTTP or WebSocket). ### Example ```javascript import { RequestHandler } from 'msw' const httpHandlers = server.listHandlers().filter((handler) => { // This will include both `http.*` and `graphql.*` handlers // while omitting any `ws.*` handlers. return handler instanceof RequestHandler }) console.log(httpHandlers) // To get only WebSocket handlers: // const wsHandlers = server.listHandlers().filter((handler) => handler instanceof WebSocketHandler) ``` ### Related - [`RequestHandler`](/docs/api/request-handler) ``` -------------------------------- ### Resolve 'http' Module Import Issue Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/integrations/react-native.mdx If you encounter an 'Unable to resolve module `http`' error, ensure you are importing `setupServer` from `msw/native` instead of `msw/node`. ```diff import { setupServer } from 'msw/node' +import { setupServer } from 'msw/native' ``` -------------------------------- ### Intercepting an EventSource URL Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/sse/intercepting-sources/index.mdx Intercept an EventSource by its URL and handle the connection. This is the basic setup for mocking SSE. ```typescript new EventSource('https://api.example.com/events') ``` ```typescript import { sse } from 'msw' export const handlers = [ sse('https://api.example.com/events', ({ request, client, server }) => { client.send({ data: 'hello world' }) }), ] ``` -------------------------------- ### Establish WebSocket Server Connection Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/ws.mdx Use `server.connect()` to establish a connection to the actual WebSocket server. This is typically done within a 'connection' event listener. ```javascript api.addEventListener('connection', ({ server }) => { server.connect() }) ``` -------------------------------- ### Generate Worker Script with `msw init` Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/best-practices/managing-the-worker.mdx Use the `msw init` command to generate the `mockServiceWorker.js` script. Replace `` with your application's public directory path. The `--save` flag is recommended for automatic updates. ```bash npx msw init --save ``` -------------------------------- ### worker.start() Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/setup-worker/start.mdx Registers the Service Worker and starts request interception. It returns a promise that resolves when the worker is ready. ```APIDOC ## Call signature The `worker.start()` method accepts an optional [Options](#options) object that you can use to customize the worker registration. By default, when called without any arguments, the `worker.start()` method registers the Service Worker served under `./mockServiceWorker.js` and starts the request interception. ```js import { setupWorker } from 'msw/browser' import { handlers } from './handlers' const worker = setupWorker(...handlers) await worker.start() // Promise<{ pending }> ``` Note that registering and activating the Service Worker is an asynchronous action. The `worker.start()` returns you a promise that resolves when the worker is ready. Do not forget to await it to prevent race conditions between the worker registration and your network-dependent code. You can see a confirmation message printed in the browser's console when MSW is active. ```sh [MSW] Mocking enabled. ``` ``` -------------------------------- ### Fetch Response with Specific Accept Header Source: https://github.com/mswjs/mswjs.io/blob/main/websites/source.mswjs.io/src/content/docs/integrations/open-api.mdx Demonstrates how to fetch a resource and specify the desired content type using the 'Accept' request header. ```javascript await fetch('/resource', { headers: { Accept: 'application/xml', }, }).then((res) => res.json()) ``` -------------------------------- ### Update Worker Imports Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/migrations/1.x-to-2.x.mdx Change the import path for browser-side worker setup functions and types from 'msw' to 'msw/browser'. ```javascript import { setupWorker } from 'msw' ``` ```javascript import { setupWorker } from 'msw/browser' ``` -------------------------------- ### Accessing Worker/Server Instance Events Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/life-cycle-events.mdx The `events` property is available on both `setupWorker` and `setupServer` instances for subscribing to life-cycle events. ```javascript // In the browser. const worker = setupWorker(...handlers) worker.events // In Node.js. const server = setupServer(...handlers) server.events ``` -------------------------------- ### Generated Handler for Base Path Source: https://github.com/mswjs/mswjs.io/blob/main/websites/source.mswjs.io/src/content/docs/integrations/open-api.mdx This is an example of a request handler generated by `fromOpenApi` when a `basePath` is specified in the OpenAPI document. ```js http.post('https://api.example.com/cart/:cartId', resolver) ``` -------------------------------- ### Generate Handlers from OpenAPI with Source Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/blog/introducing-source.mdx Shows how to import and use the `fromOpenApi` function from `@msw/source/open-api` to generate request handlers based on an OpenAPI specification file. ```javascript import { fromOpenApi } from '@msw/source/open-api' import api from './api.json' export const handlers = await fromOpenApi(api) ``` -------------------------------- ### Initialize Worker Without Handlers Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/setup-worker/index.mdx Use setupWorker without arguments to create a worker instance with no initial request handlers. You can later add handlers using worker.use(). ```javascript import { setupWorker } from 'msw/browser' const worker = setupWorker() // worker.start() // worker.use(...handlers) ``` -------------------------------- ### Enable Mocking in Node.js Application Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/integrations/node.mdx Import the `server` instance and call `.listen()` in your application's entry module to enable API mocking early on. This method is synchronous. ```javascript import { server } from './mocks/node' server.listen() // ...the rest of your Node.js application. ``` -------------------------------- ### Using server.boundary() with framework route handlers Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/setup-server/boundary.mdx Demonstrates how `server.boundary()` can be integrated with backend framework route handlers, ensuring that interception logic is confined to the scope of a specific request. ```APIDOC ## server.boundary() with framework route handlers ### Description This example shows how to use `server.boundary()` within a framework like Express to scope network request handlers for a specific route. The boundary ensures that any request interception logic, such as logging or modifying responses, is isolated to the handling of that particular route. ### Usage ```ts import express from 'express' import { http } from 'msw' import { setupServer } from 'msw/node' const server = setupServer() server.listen() const app = express() app.post('/resource', (req, res) => { // The server.boundary() creates an isolated scope for request interception. // Handlers defined within this boundary will only affect requests made during its execution. server.boundary(() => { // Example: Log all requests within this boundary. server.use( http.all('*', ({ request }) => { console.log(request.method, request.url) }) ) // Assume handleRequest processes the actual request and response. handleRequest(req, res) })() }) // Placeholder for the actual request handling logic function handleRequest(req, res) { // ... implementation details ... res.send('Resource processed') } ``` ### Notes - The `server.boundary()` function accepts arguments passed to it and returns whatever the callback function returns. This allows it to seamlessly integrate with frameworks that expect specific return types from route handlers. ``` -------------------------------- ### Composing a Mock Response Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/blog/introducing-msw-2.0.mdx Demonstrates how to construct a mock response by composing utilities like ctx.status and ctx.json. This approach was common in earlier versions of MSW. ```javascript // Constructing a response is a matter of // composing various response utilities, // like "ctx.status" and "ctx.json". res( ctx.status(201), ctx.json({ id: 'abc-123', title: 'Introducing MSW 2.0', }), ) ``` -------------------------------- ### Creating a New Apollo Client Instance Per Test Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/faq.mdx Illustrates the recommended approach for Apollo Client in tests: creating a new client instance for each test. This ensures a clean state and avoids potential issues with shared client instances across tests. ```javascript // src/apollo-client.js import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client' const httpLink = new HttpLink({ uri: 'https://example.com/graphql', }) export function makeClient() { return new ApolloClient({ cache: new InMemoryCache(), link: httpLink, }) } ``` ```javascript // test/Component.test.jsx import { makeClient } from '../src/apollo-client' it('renders the component', async () => { const client = makeClient() // ...use your client in test. }) ``` -------------------------------- ### GraphQL Query with Variables Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/graphql/intercepting-operations/variables.mdx Example of a GraphQL query that accepts variables. This query defines a `$limit` variable to filter the users returned. ```graphql query ListUsers($limit: Int!) { users(limit: $limit) { id name } } ``` -------------------------------- ### Create MSW Polyfills File Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/integrations/react-native.mdx Create a dedicated file to import the required polyfills for MSW. This file will be imported in your application's entry point. ```js // msw.polyfills.js import 'fast-text-encoding' import 'react-native-url-polyfill/auto' ``` -------------------------------- ### Custom onUnhandledRequest with isCommonAssetRequest Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/is-common-asset-request.mdx Example of using `isCommonAssetRequest` within a custom `onUnhandledRequest` callback to ignore common static asset requests. ```typescript import { isCommonAssetRequest } from 'msw' const { setupWorker } = require('msw/browser') const worker = setupWorker() worker.start({ onUnhandledRequest(request, print) { // List a custom request predicate. if (myCustomLogic(request)) { return } // Ignore common static asset requests // (i.e. tap into the default behavior). if (isCommonAssetRequest(request)) { return } // Otherwise, print a warning. print.warning() } }) ``` -------------------------------- ### Accessing the events property Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/api/life-cycle-events.mdx The `events` property is available on both `setupWorker` and `setupServer` instances. ```APIDOC ## Accessing the events property The `events` property is available on both `setupWorker` and `setupServer` instances. ```js // In the browser. const worker = setupWorker(...handlers) worker.events // In Node.js. const server = setupServer(...handlers) server.events ``` ``` -------------------------------- ### Configure `msw.workerDirectory` in `package.json` (Single Directory) Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/best-practices/managing-the-worker.mdx The `msw init --save` command stores the public directory path in `package.json`. This enables automatic worker script generation upon dependency updates. ```json // package.json { "msw": { "workerDirectory": "./public" } } ``` -------------------------------- ### Import http Namespace Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/http/index.mdx Import the `http` namespace from MSW to begin mocking HTTP requests. ```typescript import { http } from 'msw' ``` -------------------------------- ### Generated Handlers for Multiple Servers Source: https://github.com/mswjs/mswjs.io/blob/main/websites/source.mswjs.io/src/content/docs/integrations/open-api.mdx These are examples of request handlers generated when multiple server URLs are defined in the OpenAPI document's `servers` property. ```js http.get('https://prod.example.com/user', resolver) http.get('https://staging.example.com/user', resolver) ``` -------------------------------- ### Initialize MSW Worker Script Source: https://github.com/mswjs/mswjs.io/blob/main/websites/mswjs.io/src/content/docs/cli/init.mdx Use this command to copy the worker script to your application's public directory. Replace `` with the actual path. ```bash npx msw init [options] ```