{"library":"msw","title":"Mock Service Worker","description":"Mock Service Worker (MSW) is a powerful and seamless library for intercepting and mocking REST and GraphQL API requests directly at the network level, in both browser and Node.js environments. Unlike traditional mocking libraries that patch client-side request utilities, MSW leverages the Service Worker API in browsers and a custom `http` interception module in Node.js. This approach allows applications to run against mock data without any code changes, making it ideal for consistent mocking across development, unit, integration, and end-to-end testing, as well as debugging. The current stable version is 2.13.4, with frequent minor and patch releases, often several times a month, indicating active development. Its key differentiator is providing deviation-free mocking by intercepting actual network requests, ensuring a high fidelity simulation of real API interactions.","language":"javascript","status":"active","last_verified":"Tue Apr 21","install":{"commands":["npm install msw"],"cli":null},"imports":["import { setupWorker } from 'msw/browser'","import { setupServer } from 'msw/node'","import { http } from 'msw'","import { HttpResponse } from 'msw'"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import { setupWorker, http, HttpResponse } from 'msw';\n\n// Define handlers for your API requests\nconst handlers = [\n  http.get('https://example.com/api/user/:userId', ({ params }) => {\n    const { userId } = params;\n    if (userId === '123') {\n      return HttpResponse.json(\n        { id: '123', name: 'John Doe', email: 'john.doe@example.com' },\n        { status: 200 }\n      );\n    }\n    return HttpResponse.json({ message: 'User not found' }, { status: 404 });\n  }),\n  http.post('https://example.com/api/users', async ({ request }) => {\n    const newUser = await request.json();\n    console.log('New user creation request:', newUser);\n    return HttpResponse.json({ id: 'new-id', ...newUser }, { status: 201 });\n  })\n];\n\n// Create a service worker instance\nconst worker = setupWorker(...handlers);\n\n// Register the Service Worker in the browser\nworker.start({\n  onUnhandledRequest: 'warn' // Configure behavior for unhandled requests\n});\n\nconsole.log('MSW service worker started.');\n\n// Example usage: Make a fetch request that will be intercepted by MSW\nasync function demonstrateMocking() {\n  try {\n    console.log('Fetching user 123...');\n    const userResponse = await fetch('https://example.com/api/user/123');\n    const userData = await userResponse.json();\n    console.log('Fetched user (mocked):', userData);\n\n    console.log('Creating a new user...');\n    const createUserResponse = await fetch('https://example.com/api/users', {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json' },\n      body: JSON.stringify({ name: 'Jane Smith', email: 'jane.smith@example.com' })\n    });\n    const newUserData = await createUserResponse.json();\n    console.log('Created user (mocked):', newUserData);\n  } catch (error) {\n    console.error('Fetch error:', error);\n  }\n}\n\ndemonstrateMocking();","lang":"typescript","description":"This quickstart demonstrates setting up a browser-based Mock Service Worker to intercept and respond to HTTP GET and POST requests, followed by actual `fetch` calls that are intercepted by the mock server.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}