### Browser Setup and Request Handling Source: https://github.com/mswjs/msw/blob/main/README.md This snippet demonstrates how to import MSW, define request handlers for specific endpoints, and start the Service Worker in a browser environment. It shows how to mock a GET request to a GitHub URL and return a JSON response with a custom status. ```javascript import { http, HttpResponse } from 'msw' import { setupWorker } from 'msw/browser' const worker = setupWorker( http.get('https://github.com/octocat', ({ request, params, cookies }) => { return HttpResponse.json( { message: 'Mocked response', }, { status: 202, statusText: 'Mocked status', }, ) }), ) await worker.start() ``` -------------------------------- ### Install and start project Source: https://github.com/mswjs/msw/blob/main/CONTRIBUTING.md Commands to initialize the project environment using PNPM. ```bash $ cd msw $ pnpm install $ pnpm start ``` -------------------------------- ### Node.js Setup with Express Server Source: https://github.com/mswjs/msw/blob/main/README.md This example shows how to use MSW with Node.js and Express. It sets up a server instance and uses `server.boundary()` to scope request interception to a specific Express route handler. Inside the handler, it defines a mock for an external API call. ```javascript import express from 'express' import { http, HttpResponse } from 'msw' import { setupServer } from 'msw/node' const app = express() const server = setupServer() app.get( '/checkout/session', server.boundary((req, res) => { server.use( http.get( 'https://api.stripe.com/v1/checkout/sessions/:id', ({ params }) => { return HttpResponse.json({ id: params.id, mode: 'payment', status: 'open', }) }, ), ) handleSession(req, res) }), ) ``` -------------------------------- ### Define Browser Mock Example Source: https://github.com/mswjs/msw/blob/main/CONTRIBUTING.md Create a mock definition file for browser integration tests using setupWorker. ```js // test/browser/example.mocks.ts import { http, HttpResponse } from 'msw' import { setupWorker } from 'msw/browser' const worker = setupWorker( http.get('/books', () => { return HttpResponse.json([ { id: 'ea42ffcb-e729-4dd5-bfac-7a5b645cb1da', title: 'The Lord of the Rings', publishedAt: -486867600, }, ]) }), ) worker.start() ``` -------------------------------- ### Write a unit test Source: https://github.com/mswjs/msw/blob/main/CONTRIBUTING.md Example of a unit test using Vitest syntax. ```ts // src/utils/multiply.test.ts import { multiply } from './multiply' test('multiplies two given numbers', () => { expect(multiply(2, 3)).toEqual(6) }) ``` -------------------------------- ### Execute Browser Integration Test Source: https://github.com/mswjs/msw/blob/main/CONTRIBUTING.md Use Playwright to load the mock example and assert the response in a browser environment. ```ts // test/browser/example.test.ts import * as path from 'path' import { test, expect } from './playwright.extend' test('returns a mocked response', async ({ loadExample, fetch }) => { // Compile the given usage example on runtime. await loadExample(new URL('./example.mocks.ts', import.meta.url)) // Perform the "GET /books" request in the browser. const res = await fetch('/books') // Assert the returned response body. expect(await res.json()).toEqual([ { id: 'ea42ffcb-e729-4dd5-bfac-7a5b645cb1da', title: 'The Lord of the Rings', publishedAt: -486867600, }, ]) }) ``` -------------------------------- ### Intercept GET Request with MSWJS Source: https://github.com/mswjs/msw/blob/main/test/browser/msw-api/setup-worker/scenarios/iframe-isolated-response/two.html Use `worker.use` with `http.get` to intercept GET requests to './resource'. The `isolatedResolver` function ensures the mock only responds if the referrer matches the current location. This is useful for isolating mock behavior. ```javascript window.request = () => { const { worker, http } = window.parent.msw function isolatedResolver(resolver) { return (info) => { if (info.request.referrer !== location.href) { return } return resolver(info) } } worker.use( http.get( './resource', isolatedResolver(({ request }) => { return new Response('two') }), ), ) return fetch('./resource') .then((response) => response.text()) .then((data) => { const node = document.createElement('p') node.innerText = data document.body.appendChild(node) }) .catch((error) => console.error(error)) } document.addEventListener('click', window.request) ``` -------------------------------- ### Build the library Source: https://github.com/mswjs/msw/blob/main/CONTRIBUTING.md Command to compile the project. ```bash $ pnpm build ``` -------------------------------- ### Create a unit test file Source: https://github.com/mswjs/msw/blob/main/CONTRIBUTING.md Command to generate a new test file for a specific utility. ```bash $ touch src/utils/multiply.test.ts ``` -------------------------------- ### Define and Run Node.js Integration Test Source: https://github.com/mswjs/msw/blob/main/CONTRIBUTING.md Implement a self-contained integration test for Node.js using setupServer. ```ts // test/node/example.test.ts import { http, HttpResponse } from 'msw' import { setupServer } from 'msw/node' const server = setupServer( http.get('/books', () => { return HttpResponse.json([ { id: 'ea42ffcb-e729-4dd5-bfac-7a5b645cb1da', title: 'The Lord of the Rings', publishedAt: -486867600, }, ]) }), ) beforeAll(() => server.listen()) afterAll(() => server.close()) test('returns a mocked response', async () => { const res = await fetch('/books') expect(await res.json()).toEqual([ { id: 'ea42ffcb-e729-4dd5-bfac-7a5b645cb1da', title: 'The Lord of the Rings', publishedAt: -486867600, }, ]) }) ``` -------------------------------- ### Run unit tests Source: https://github.com/mswjs/msw/blob/main/CONTRIBUTING.md Commands to execute specific or all unit tests. ```bash $ pnpm test:unit src/utils/multiply.test.ts ``` ```bash $ pnpm test:unit ``` -------------------------------- ### Run Browser Integration Tests Source: https://github.com/mswjs/msw/blob/main/CONTRIBUTING.md Commands to execute all or specific browser integration tests. ```sh pnpm test:browser ``` ```sh pnpm test:browser ./test/browser/example.test.ts ``` -------------------------------- ### Run Node.js Integration Tests Source: https://github.com/mswjs/msw/blob/main/CONTRIBUTING.md Commands to execute all or specific Node.js integration tests. ```sh pnpm test:node ``` ```sh pnpm test:node ./test/node/example.test.ts ``` -------------------------------- ### Git workflow commands Source: https://github.com/mswjs/msw/blob/main/CONTRIBUTING.md Standard sequence for creating, committing, and pushing a feature branch. ```bash # Checkout the default branch and ensure it's up-to-date $ git checkout main $ git pull --rebase # Create a feature branch $ git checkout -b feature/graphql-subscriptions # Commit the changes $ git add . $ git commit # Follow the interactive prompt to compose a commit message # Push $ git push -u origin feature/graphql-subscriptions ``` -------------------------------- ### Make FormData Request Source: https://github.com/mswjs/msw/blob/main/test/browser/rest-api/request/body/body-form-data.page.html This function demonstrates how to construct and send a FormData request with various data types including strings, files, and JSON blobs. ```javascript window.makeRequest = () => { const data = new FormData() data.set('name', 'Alice') data.set('file', new File(['hello world'], 'file.txt')) data.set( 'ids', new Blob([ JSON.stringify([1, 2, 3]) ], { type: 'application/json' }), ) fetch('/formData', { method: 'POST', body: data, }) } ``` -------------------------------- ### Fetch Request and DOM Update Source: https://github.com/mswjs/msw/blob/main/test/browser/msw-api/setup-worker/scenarios/iframe/app.html Triggers a fetch request upon a click event and appends the returned first name to the document body. ```javascript window.request = () => { fetch('./user') .then((res) => res.json()) .then((data) => { const node = document.createElement('p') node.setAttribute('id', 'first-name') node.innerText = data.firstName document.body.appendChild(node) }) } document.addEventListener('click', window.request) ``` -------------------------------- ### Intercepting requests with MSW in the browser Source: https://github.com/mswjs/msw/blob/main/test/browser/msw-api/setup-worker/scenarios/iframe-isolated-response/one.html Uses an isolated resolver to ensure requests are only intercepted if they originate from the current location. Requires the MSW worker to be available in the parent window. ```javascript window.request = () => { const { worker, http } = window.parent.msw function isolatedResolver(resolver) { return (info) => { if (info.request.referrer !== location.href) { return } return resolver(info) } } worker.use( http.get( './resource', isolatedResolver(({ request }) => { return new Response('one') }), ), ) return fetch('./resource') .then((response) => response.text()) .then((data) => { const node = document.createElement('p') node.innerText = data document.body.appendChild(node) }) .catch((error) => console.error(error)) } document.addEventListener('click', window.request) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.