4

I am using NextJs along with Cypress and MSW. I want to use the MSW worker in Cypress to flexibly mock responses for my api request along the test to have a common mocking tool for all types of tests.

The MSW handlers in the worker setup (in NextJs) is intercepting the request from the Cypress test run without any issue. But when I define a runtime request handler in Cypress to overwrite an existing handler or to add a test-specific handler, the api request does not get intercepted.

Here are the relevant files:

./test/server/testWorker.ts

import { graphql, setupWorker } from "msw";
import { handlers } from "./serverHandlers";

const worker = setupWorker(...handlers);

window.msw = {
  worker,
  graphql,
};

export * from "msw";
export { worker };

./test/server/index.ts

async function initMocks() {
  if (typeof window !== "undefined") {
    const { worker } = await import("./testWorker");
    worker.start();
  }
}

initMocks();

export {};

./_app.tsx

...
if (process.env.NEXT_PUBLIC_API_MOCKING === "enabled") {
  require("../test/server");
}

function MyApp({....
...

./cypress/e2e/test.cy.ts

describe("test", () => {
  const data = buildTestData();
  beforeEach(() => {
    cy.visit("/");
    cy.window().then((window) => {
      const { worker, graphql } = window.msw;
// This runtime request handler does not work
      worker.use(
        graphql
          .link("https://example/graphql.json")
          .query(/fetchdata/i, (req, res, ctx) => {
            return res(
              ctx.data({
                data
              })
            );
          })
      );
    });
  });
...

The worker.printHandlers() command shows that the runtime request handler in the console is registered but the request was not intercepted. MSW warns me 'captured a request without a matching request handler' in my console.

I am grateful for any help!

dnyn
  • 51
  • 4

0 Answers0