Mock Service Worker (MSW)

repository·main·Indexed 41 days ago

https://github.com/mswjs/mswjs.io

A library for API mocking in development and testing environments. MSW 2.0+ utilizes standard Fetch API Request and Response objects, supports WebSocket mocking with event-based APIs, and provides a Server Boundary API (v2.2.0+) for isolating request handler overrides in concurrent Node.js tests.

Tokens
81K
Snippets
312
Records
376
Agent score
48%

What's inside MSW

  1. What is Source and when to use it

    main

    Source is a library designed to generate Mock Service Worker (MSW) request handlers from existing network data or specifications.

    Instead of writing handlers manually, you can use Source to bridge the gap when:

    • Migrating large existing test suites to MSW.
    • Writing regression tests for network scenarios that were reproduced elsewhere (e.g., in a browser).

    Source allows you to take inputs like OpenAPI documents or HAR files and transform them into reliable, reproducible MSW request handlers. This is particularly useful for replaying network-related issues by saving a browser's network activity as an *.har file and using Source to generate the corresponding handlers for your test suite.

  2. Introduction to Mock Service Worker (MSW)

    main

    Mock Service Worker (MSW) is an API mocking library designed for both the browser and Node.js. It allows you to intercept, observe, and respond to outgoing network requests using mocked responses.

    MSW functions as a standalone API mocking layer, providing a single source of truth for network behavior that can be integrated across various tools and environments (development, integration testing, E2E testing, Storybook, etc.).

  3. MSW 2.0 Requirements and Improvements

    main

    MSW 2.0 includes several architectural improvements:

    • Node.js Support: Deprecates support for Node.js ≤ v16. It requires Node.js v18+ (or later versions that support the standard Fetch API).
    • Module System: Full compatibility with ESM (ECMAScript Modules).
    • Performance: Improved internal architecture, refined interception algorithms in Node.js, and proper code splitting.
  4. Access Mock Service Worker documentation and examples

    main
    The mswjs.io repository serves as the official documentation hub for the Mock Service Worker (MSW) library. You can find comprehensive guides, API references, and setup instructions at the main documentation site, or explore practical implementations in the official examples repository.
  5. Benefits of using MSW for HTTP mocking

    main

    Using MSW for HTTP mocking provides several advantages:

    • Client-agnostic: Intercepts any HTTP request regardless of the client used (e.g., fetch(), Axios, etc.).
    • Seamless: Requires zero changes to your application code; requests are intercepted at the network level.
    • Reusable: Mocks can be used for local development, automated testing, debugging, and app showcases.
    • Type-safe: Supports annotation of path parameters and request/response body types to ensure mocks remain synchronized with your data structures.
  6. Best practices for network descriptions

    main

    To improve the quality and maintainability of your network descriptions, follow these core best practices:

    • Structuring handlers: Strategies for managing a large number of request handlers effectively.
    • Network behavior overrides: How to override network behaviors during runtime.
    • Avoid request assertions: Guidance on why you should avoid asserting requests directly.
    • Custom request predicates: Techniques to intercept requests using custom criteria.
    • Dynamic mock scenarios: How to apply different network scenarios at runtime.
    • Managing the worker: Best practices for managing worker script updates.
  7. Mock GraphQL APIs with MSW

    main

    Mock Service Worker (MSW) provides first-class support for mocking GraphQL APIs via the graphql namespace exported from msw. This allows you to intercept and mock GraphQL operations for development, testing, and debugging.

    Key Features

    • Client-agnostic: Works with any GraphQL client (Apollo, Relay, URQL, graphql-request) or even plain fetch() calls, as long as they comply with the GraphQL Specification.
    • Specification-compliant: MSW uses the graphql package to parse operations, meaning it will refuse operations that violate the spec.
    • Type-safe: You can reuse type definitions from tools like GraphQL Code Generator in your mocks to ensure they stay in sync with your schema.
    • No Mock Providers: Unlike some other libraries, you don't need to wrap your application in special <MockProvider> components, leading to a cleaner test setup.
    import { graphql } from 'msw'
  8. What is HttpResponse and when to use it

    main

    The HttpResponse class is a drop-in replacement for the Fetch API Response class. While you can use native Response instances in your MSW response resolvers, HttpResponse is highly recommended because it enables features not available in the standard Fetch API, such as mocking response cookies.

    HttpResponse respects the standard Response constructor signature and methods to ensure familiarity with web fundamentals while providing convenient shorthand methods for common response types.

  9. What is Source and how does it work?

    main

    Source is an open-source library designed to work alongside Mock Service Worker (MSW) to automate the generation of request handlers. Instead of manually writing handlers, Source follows the functional pattern of X -> RequestHandler[], where X is a source of truth (like an API specification or a network recording) and the output is an array of MSW request handlers.

    This allows you to lift your source of truth (e.g., an OpenAPI document) directly into your testing environment, ensuring your mocks stay in sync with your actual API definitions.

    import { fromOpenApi } from '@msw/source/open-api'
    import api from './api.json'
    
    export const handlers = await fromOpenApi(api)
  10. Understand the Astro project structure

    main

    An Astro project follows a specific directory convention for routing and assets:

    • src/pages/: Contains .astro or .md files. Each file in this directory is exposed as a route based on its filename.
    • src/components/: A directory for reusable components (Astro, React, Vue, Svelte, Preact, etc.).
    • src/layouts/: Typically used to store layout components.
    • public/: Contains static assets like images or favicons that are served directly.
    • package.json: Defines project dependencies and scripts.
    /
    ├── public/
    │   └── favicon.svg
    ├── src/
    │   ├── components/
    │   │   └── Card.astro
    │   ├── layouts/
    │   │   └── Layout.astro
    │   └── pages/
    │       └── index.astro
    └── package.json
  11. Understand Initial vs Runtime request handlers

    main

    MSW distinguishes between two types of request handlers:

    1. Initial request handlers: The list of handlers provided during the initial setup via setupWorker() or setupServer(). These act as your baseline network description or fallback.
    2. Runtime request handlers: Handlers added after the API mocking has been enabled using the .use() method.

    Runtime handlers are prepended to the initial handlers, meaning they take priority when handling requests. This allows you to define a stable network environment and then override specific behaviors for individual tests or specific application states.

    import { http, HttpResponse } from 'msw'
    import { setupServer } from 'msw/node'
    
    const server = setupServer(
      // These are the initial request handlers.
      http.get('/resource', () => {
        return HttpResponse.text('Fallback')
      })
    )
    
    server.use(
      // These are the runtime request handlers.
      http.post('/login', () => {
        return new HttpResponse()
      })
    )