Skip to content

Latest commit

 

History

History
56 lines (32 loc) · 2.6 KB

File metadata and controls

56 lines (32 loc) · 2.6 KB

Cypress + MSW

Mock Service Worker usage example with Cypress.

Edit in CodeSandbox

General

This example shows how to reuse existing MSW handlers while keeping Cypress cy.intercept() as the interception layer.

  1. Cypress intercepts the request.
  2. The intercepted request is converted into a Fetch API Request.
  3. MSW handlers are executed manually.
  4. The resulting Response is converted into a Cypress req.reply() payload.

Use mocks/handlers.ts as the single source of mocked behavior and wire the bridge from cypressExample.ts into your Cypress support code.

Why use this pattern?

Many Cypress projects already rely on cy.intercept() as the primary network interception mechanism in end-to-end tests. At the same time, teams often use MSW as the single source of truth for mocked API behavior across local development, Storybook, component tests, and integration tests.

Without this pattern, teams usually duplicate mocks:

  • MSW handlers for development and component tests.
  • Cypress cy.intercept() mocks for E2E tests.

Reusing MSW handlers from Cypress helps avoid that duplication and keeps mock behavior aligned across environments.

Benefits

  1. Mock definitions stay consistent.

    When mocks exist in two places, they can drift apart. Reusing MSW handlers in Cypress ensures the same mocked responses are used everywhere.

  2. Business logic is not duplicated.

    MSW handlers often include conditional responses, pagination, error scenarios, or state transitions. This approach lets Cypress reuse that logic instead of reimplementing it.

  3. Cypress remains in control of interception.

    Cypress still provides request assertions, aliasing, waiting, and network debugging in the Cypress UI. In this setup, Cypress is the interception layer while MSW defines the responses.

  4. No service worker is required in Cypress.

    Since Cypress already intercepts network traffic, you can resolve MSW handlers manually without running setupWorker() in the test environment.

Summary

This pattern combines the strengths of both tools:

Tool Responsibility
Cypress Network interception and test control
MSW Mock API behavior and response definitions

As a result, you get a single source of truth for mocks, no duplicated mock logic, full Cypress network tooling, and no service worker requirement in tests.