Skip to content

Can't overwrite handlers from within test #21

@kleinfreund

Description

@kleinfreund

Minimal reproduction: https://github.com/kleinfreund/msw-playwright-reproduction

I wrote a basic test that only passes if an msw handler set-up in that test is applied instead of the default handler used by the application:

import { expect } from "@playwright/test";
import { http, HttpResponse } from "msw";

import { test } from "../playwright.setup.js";

test("has expected list items", async ({ network, page }) => {
  network.use(
    http.get(
      "/api/list",
      () => (HttpResponse.json([
        { name: "Alice" },
      ])),
    ),
  );

  await page.goto("/");

  const items = await page.getByRole("listitem");
  await expect(items).toHaveCount(1);
});

The setup file:

import { createNetworkFixture } from "@msw/playwright";
import { test as testBase } from "@playwright/test";

import { handlers } from "./mocks/handlers.js";

export const test = testBase.extend({
  network: createNetworkFixture({ initialHandlers: handlers }),
});

And the application:

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>msw-playwright-reproduction</title>
  </head>
  <body>
    <ul></ul>

    <script type="module">
      const { worker } = await import("./mocks/browser.js");
      await worker.start();

      const response = await fetch("/api/list")
      const items = await response.json()
      const list = document.querySelector("ul")
      list.innerHTML = items.map((item) => `<li>${item.name}</li>`).join("")
    </script>
  </body>
</html>

I skipped any sort environment variable switch for the sake of keeping the reproduction minimal. In a real application, the first two script lines would only run during tests or development.

The test fails (run with npx playwright test) but I expect it to pass. Symptomatically, I'd say the application just never sees handlers added in tests, but that's just an assumption.

What am I doing wrong?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions