Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .github/workflows/examples.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,20 @@ on:
workflow_dispatch:

jobs:
cypress:
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- uses: pnpm/action-setup@v4
with:
version: 9.15.3
- run: pnpm install --filter with-cypress
- run: pnpm test --filter with-cypress
- run: pnpm --filter with-cypress run test:types

angular:
runs-on: ubuntu-latest
steps:
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ A collection of usage examples of [Mock Service Worker](https://github.com/mswjs

### Test frameworks

- Cypress
- [Cypress](./examples/with-cypress)
- [Jest](./examples/with-jest)
- [Jest (JSDOM)](./examples/with-jest-jsdom)
- [Karma](./examples/with-karma)
Expand Down
56 changes: 56 additions & 0 deletions examples/with-cypress/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Cypress + MSW

[Mock Service Worker](https://github.com/mswjs/msw) usage example with [Cypress](https://github.com/cypress-io/cypress).

[![Edit in CodeSandbox](https://assets.codesandbox.io/github/button-edit-lime.svg)](https://codesandbox.io/p/sandbox/github/mswjs/examples/tree/main/examples/with-cypress)

## General

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

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

Use [`mocks/handlers.ts`](./mocks/handlers.ts) as the single source of mocked behavior and wire the bridge from [`cypressExample.ts`](./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.

1. 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.

1. 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.

1. 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.
15 changes: 15 additions & 0 deletions examples/with-cypress/cypressExample.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { handlers } from './mocks/handlers'
import { resolveMswResponse } from './mswHelpers'

beforeEach(() => {
cy.intercept('POST', '/graphql', async (req) => {
const mswResponse = await resolveMswResponse(req, handlers)

if (mswResponse) {
req.reply(mswResponse)
return
}

req.continue()
})
})
54 changes: 54 additions & 0 deletions examples/with-cypress/example.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { handlers } from './mocks/handlers'
import { resolveMswResponse } from './mswHelpers'
import type { CypressRequest } from './types'

it('resolves a matching GraphQL request using MSW handlers', async () => {
const request: CypressRequest = {
method: 'POST',
url: 'https://api.example.com/graphql',
headers: {
'content-type': 'application/json',
},
body: {
operationName: 'GetUser',
query: `
query GetUser {
user {
id
firstName
lastName
}
}
`,
},
}

await expect(resolveMswResponse(request, handlers)).resolves.toEqual(
expect.objectContaining({
statusCode: 200,
headers: expect.objectContaining({
'content-type': 'application/json',
}),
body: {
data: {
user: {
id: 'abc-123',
firstName: 'John',
lastName: 'Maverick',
},
},
},
}),
)
})

it('returns null when no handler matches the intercepted request', async () => {
const request: CypressRequest = {
method: 'GET',
url: 'https://api.example.com/unknown',
headers: {},
body: undefined,
}

await expect(resolveMswResponse(request, handlers)).resolves.toBeNull()
})
9 changes: 9 additions & 0 deletions examples/with-cypress/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { Config } from 'jest'

export default {
rootDir: '.',
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
transform: {
'^.+\\.tsx?$': '@swc/jest',
},
} satisfies Config
3 changes: 3 additions & 0 deletions examples/with-cypress/jest.setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
afterEach(() => {
jest.restoreAllMocks()
})
23 changes: 23 additions & 0 deletions examples/with-cypress/mocks/handlers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { graphql, HttpResponse } from 'msw'

type GetUserQuery = {
user: {
id: string
firstName: string
lastName: string
}
}

export const handlers = [
graphql.query<GetUserQuery>('GetUser', () => {
return HttpResponse.json({
data: {
user: {
id: 'abc-123',
firstName: 'John',
lastName: 'Maverick',
},
},
})
}),
]
83 changes: 83 additions & 0 deletions examples/with-cypress/mswHelpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import type { RequestHandler } from 'msw'
import type { CypressRequest, CypressStaticResponse } from './types'

const getRequestBody = ({ body, method }: CypressRequest) => {
if (body == null || method === 'GET' || method === 'HEAD') {
return undefined
}

if (
typeof body === 'string' ||
body instanceof Blob ||
body instanceof FormData ||
body instanceof URLSearchParams ||
body instanceof ArrayBuffer
) {
return body
}

return JSON.stringify(body)
}

const getRequestHeaders = (
headers: CypressRequest['headers'],
): Record<string, string> => {
return Object.fromEntries(
Object.entries(headers).map(([key, value]) => [
key,
Array.isArray(value) ? value.join(', ') : String(value),
]),
)
}

export function createMswRequest(req: CypressRequest) {
return new Request(req.url, {
method: req.method,
headers: getRequestHeaders(req.headers),
body: getRequestBody(req),
})
}

export async function toCypressResponse(
response: Response,
): Promise<CypressStaticResponse> {
const textBody = await response.text()
const headers: Record<string, string> = {}

response.headers.forEach((value, key) => {
headers[key] = value
})

if (!textBody.length) {
return {
statusCode: response.status,
headers,
}
}

return {
statusCode: response.status,
headers,
body: /json/i.test(response.headers.get('content-type') ?? '')
? JSON.parse(textBody)
: textBody,
}
}

export async function resolveMswResponse(
req: CypressRequest,
handlers: RequestHandler[],
): Promise<CypressStaticResponse | null> {
const request = createMswRequest(req)
const requestId = `${req.method}:${req.url}:${Date.now()}`

for (const handler of handlers) {
const result = await handler.run({ request, requestId })

if (result?.response) {
return toCypressResponse(result.response)
}
}

return null
}
19 changes: 19 additions & 0 deletions examples/with-cypress/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "with-cypress",
"type": "module",
"scripts": {
"test": "jest",
"test:types": "tsc --noEmit -p tsconfig.json"
},
"devDependencies": {
"@swc/core": "^1.3.55",
"@swc/jest": "^0.2.26",
"@types/jest": "^29.5.1",
"@types/node": "^18",
"cypress": "^12.17.4",
"jest": "^29.5.0",
"msw": "2.11.2",
"ts-node": "^10.9.2",
"typescript": "^5.0.4"
}
}
11 changes: 11 additions & 0 deletions examples/with-cypress/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"module": "esnext",
"moduleResolution": "bundler",
"lib": ["dom", "esnext"],
"skipLibCheck": true,
"types": ["cypress"]
},
"include": ["./cypressExample.ts", "./mswHelpers.ts", "./mocks/**/*.ts", "./types.ts"]
}
12 changes: 12 additions & 0 deletions examples/with-cypress/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export type CypressRequest = {
body: unknown
headers: Record<string, string | string[]>
method: string
url: string
}

export type CypressStaticResponse = {
statusCode: number
headers?: Record<string, string>
body?: string | object | boolean | ArrayBuffer | null
}
Loading