3

I have a Nextjs project with tests in playwright and for mocking API, I am using Mock Service Worker (MSW) library.

I have installed and set up everything and also when I run the MSW worker in the _app.tsx file, it mocks the API correctly.

Here is my index.tsx that displays either "John" or "Failed" depending on API call to http://localhost:500/user

import React, { useState } from "react";

export default function Home() {
  const [user, setUser] = useState<any>();
  const [error, setError] = useState<string>();

  const fetchUser = async () => {
    try {
      const response = await fetch("http://localhost:5000/user");
      const user = await response.json();
      setUser(user);
    } catch (error) {
      console.log(error);
      setError("Failed");
    }
  };

  return (
    <div>
      {error && <div data-testid="content">{error}</div>}
      {user && <div data-testid="content">{user.name}</div>}
      <button data-testid="btn" onClick={() => fetchUser()}>
        Submit
      </button>
    </div>
  );
}

But when I use the MSW worker and define the request handler in the playwright test file, the test fails. Here is the playwright test file:

import { test, expect } from "@playwright/test";
import { setupWorker, rest } from "msw";

test.describe("Request tests", () => {
  test.beforeAll(() => {
    if (typeof window !== "undefined") {
      const worker = setupWorker(
        rest.get("http://localhost:5000/user", (req, res, ctx) => {
          return res(ctx.status(200), ctx.json({ name: "John" }));
        })
      );
      worker.start();
    }
  });

  test.beforeEach(async ({ page }) => {
    await page.goto("http://localhost:3000/");
  });

  test("should display John when submit is clicked", async ({ page }) => {
    await page.locator("[data-testid=btn]").click();
    await expect(page.locator("[data-testid=content]")).toContainText("John");
  });
});

The test fails even though I have defined the MSW request handler but it is not mocking the response and therefore we do not get the text John on the page.

What could be the reason for the request handler not working? Am I using it incorrectly?

Here's the link to the github repo - https://github.com/rajmasha/nextjs-testing

Raj
  • 1,928
  • 3
  • 29
  • 53

1 Answers1

1

I bet it's not working because you start your worker in "playwright" context but not in browser's. So page never start worker and can't intercept any request. Also seems like playwright supports service workers only.

Seems like now you should wrap playwright's mocking with server based msw solution.

I've found this package https://github.com/valendres/playwright-msw . You can check the idea here

Mike Yermolayev
  • 159
  • 1
  • 11