Skip to content

e2e testing (with playwright) - mocking HTTP requests in middleware doesn't work #76436

Answered by icyJoseph
FransJoakim asked this question in Help
Discussion options

You must be logged in to vote

Could you use an instrumentation file, check for edge runtime, and try to mock from there, with msw/mentoss? https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation

Quickly tested this, and it looks like it works:

// instrumentation
export async function register() {
  if (process.env.NEXT_RUNTIME === 'edge') { 
  // add another env var that signals Playwright E2E
    const mentoss = await import("mentoss")

    const server = new mentoss.MockServer("https://api.example.com");
    const mocker = new mentoss.FetchMocker({
      servers: [server]
    });

    mocker.mockGlobal();

    server.get("/ping", { status: 200, body: JSON.stringify({ foo: 'data' }) });
    s…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Answer selected by FransJoakim
Comment options

You must be logged in to vote
1 reply
@icyJoseph
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet
2 participants