Skip to Content
Octopus Energy Packages

MSW

Mock HTTP and GraphQL requests, set response cookies, and wait for browser queries

Use Mock Service Worker (MSW) handlers to return test data from HTTP and GraphQL requests. Register each override before navigation, then assert the UI that your app renders from the response.

Choose your installed MSW major when setting up the helpers below. The test examples use msw.http and msw.graphql from the fixture and work with either version. See installation and migration.

Set a default response

Add a handler to the helper when every test needs a response for the same endpoint:

lib/playwright/test.ts
import { createPlaywrightHelpers } from "@octopus-energy/playwright/msw/v2";
import { http, HttpResponse } from "msw";

export const { test, expect } = createPlaywrightHelpers({
  defaultHandlers: [
    http.get("https://api.example.test/user", () => {
      return HttpResponse.json({ name: "Taylor" });
    }),
  ],
});

Keep any .extend(...) calls for configuration or authentication fixtures after creating the base helper.

Override the HTTP response

Use msw.use(...) to override the default for one test, before the first fetch. The fixture also exposes msw.http and msw.graphql, so handlers created inside a test or reusable fixture can use the factories matching its MSW major without separate imports:

tests/playwright/mock-user.spec.ts
import { HttpResponse } from "msw";
import { expect, test } from "../../lib/playwright/test";

test("shows the mocked user", async ({ page, msw }) => {
  msw.use(
    msw.http.get("https://api.example.test/user", () => {
      return HttpResponse.json({ name: "Alex" });
    }),
  );

  await page.goto("/mock-user");
  const heading = page.getByRole("heading", {
    name: "Hello, Alex",
    exact: true,
  });
  await expect(heading).toBeVisible();
});

Run the test from your app root:

npm exec -- playwright test tests/playwright/mock-user.spec.ts

The next test starts with the default response again. Match an absolute URL for upstream requests, including their actual path.

Both bridges mock HTTP and GraphQL, not WebSocket, SSE, or streaming connections. Handlers are captured when a request starts, so later overrides affect subsequent requests. Generator handlers restart in the next test. Await mocked requests or handle request.signal: teardown fails if resolvers outlive cancellation, and cleanup errors override test.fail() to recycle the worker.

Mock a GraphQL query

Install the GraphQL client and its peer dependency:

npm i graphql-request graphql

Add a page that queries a GraphQL endpoint when you click Load profile:

Use a client component for the button and browser request:

app/profile/page.tsx
"use client";

import { GraphQLClient } from "graphql-request";
import { useState } from "react";

const client = new GraphQLClient("/api/graphql");

export default function ProfilePage() {
  const [name, setName] = useState("");

  async function loadProfile() {
    const { user } = await client.request<{ user: { name: string } }>(
      "query GetUser { user { name } }",
    );
    setName(user.name);
  }

  return (
    <main>
      <button onClick={loadProfile}>Load profile</button>
      {name ? <h1>{name}</h1> : null}
    </main>
  );
}

Register a query handler, open the page, and click the button. The mock supplies the endpoint response without an API route handler:

tests/playwright/profile.spec.ts
import { HttpResponse } from "msw";
import { expect, test } from "../../lib/playwright/test";

test("shows the profile name", async ({ page, msw }) => {
  msw.use(
    msw.graphql.link("http://localhost:3000/api/graphql").query("GetUser", () => {
      return HttpResponse.json({ data: { user: { name: "Alex" } } });
    }),
  );

  await page.goto("/profile");
  await page.getByRole("button", { name: "Load profile" }).click();
  const heading = page.getByRole("heading", { name: "Alex", exact: true });
  await expect(heading).toBeVisible();
});

Match the operation name exactly and return the fields your app queries. msw.graphql.link(...) scopes the handler to one endpoint in either MSW version. Replace http://localhost:3000/api/graphql with your application’s GraphQL endpoint when it differs.

Set cookies from a mocked response

Mocked browser fetch and XMLHttpRequest (XHR) responses preserve Set-Cookie headers, including multiple cookies. The browser applies its normal cookie rules; the helper does not call context.addCookies(...). Add a page that sends the browser request when you click Set cookie:

Use a client component to send the browser POST:

app/cookie-test/page.tsx
"use client";

import { useState } from "react";

export default function CookieTestPage() {
  const [saved, setSaved] = useState(false);

  async function saveCookie() {
    const response = await fetch("/api/mock-session", { method: "POST" });
    if (response.ok) setSaved(true);
  }

  return (
    <main>
      <button onClick={saveCookie}>Set cookie</button>
      {saved ? <p>Cookie saved</p> : null}
    </main>
  );
}

Mock the endpoint response and assert both the confirmation and stored cookie. The mock supplies the response, so this example doesn’t need an API route handler:

tests/playwright/cookies.spec.ts
import { HttpResponse } from "msw";
import { expect, test } from "../../lib/playwright/test";

test("stores a response cookie", async ({ page, msw, context, baseURL }) => {
  const headers = {
    "Set-Cookie": "demo_session=test_session; Path=/; HttpOnly",
  };
  msw.use(
    msw.http.post(`${baseURL}/api/mock-session`, () => {
      return HttpResponse.json({ saved: true }, { headers });
    }),
  );

  await page.goto("/cookie-test");
  await page.getByRole("button", { name: "Set cookie" }).click();
  await expect(page.getByText("Cookie saved")).toBeVisible();
  const cookies = await context.cookies();
  const cookie = cookies.find(({ name }) => name === "demo_session");
  expect(cookie).toMatchObject({ value: "test_session" });
});

Request Cookie headers pass through unchanged; browser-context cookies are not injected into server-side fetches. Forward any required cookies explicitly.

Use your app’s cookie name and attributes. A cookie for an upstream API domain doesn’t authenticate your app’s domain. Server-side mocked responses retain Set-Cookie headers without changing browser cookies. Your application must explicitly forward those cookies to its browser response, including from Server Actions. To seed browser cookies before navigation instead, use context.addCookies(...).

Wait for a browser GraphQL query

Use waitForGraphQLResponse to inspect the browser response from the /profile page above. Pass the button click as the action so the helper starts listening before the request:

tests/playwright/profile-response.spec.ts
import { HttpResponse } from "msw";
import { expect, test } from "../../lib/playwright/test";

test("waits for GetUser", async ({ page, msw, waitForGraphQLResponse }) => {
  msw.use(
    msw.graphql.link("http://localhost:3000/api/graphql").query("GetUser", () => {
      return HttpResponse.json({ data: { user: { name: "Alex" } } });
    }),
  );
  await page.goto("/profile");
  const response = await waitForGraphQLResponse("GetUser", async () => {
    await page.getByRole("button", { name: "Load profile" }).click();
  });

  expect(response.ok()).toBe(true);
  const heading = page.getByRole("heading", { name: "Alex", exact: true });
  await expect(heading).toBeVisible();
});

The helper only observes browser responses, not server-side upstream calls. MSW 2 waits for POST responses; MSW 3 supports GET and POST. Both require status 200 and don’t report GraphQL errors for you. When waiting for a mutation with MSW 2, pass a generated named mutation document rather than an operation name. For other response types, use Playwright’s page.waitForResponse(...). See the response-wait API for matching limits, including mutation operation names.

On this page