e2e testing (with playwright) - mocking HTTP requests in middleware doesn't work #76436
-
SummaryTo be able to test my application using Playwright I need to mock access check requests being done in the middleware. Next middleware runs before anything else though, so it seems like these http requests run no matter what I do. Does anyone know how to mock such requests in the middleware? Additional informationI am using Experimental test mode for Playwright
"@playwright/test": "^1.50.1",
"msw": "^2.7.2", ExampleNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
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' }) });
server.get("/ping", { status: 200, body: JSON.stringify({ foo: 'data' }) });
server.get("/ping", { status: 200, body: JSON.stringify({ foo: 'data' }) });
server.get("/ping", { status: 200, body: JSON.stringify({ foo: 'data' }) });
}
} Mentoss is single use routes only, but this should just work with MSW as well. And then my middleware does: import type { NextRequest } from 'next/server'
export async function middleware(request: NextRequest) {
const data = await fetch("https://api.example.com/ping").then((res) => res.json());
console.log(data)
} And I can see the data correctly logged. |
Beta Was this translation helpful? Give feedback.
-
Thanks for the input! I am struggling with MSW when trying to do this, because setting up the MSW server with msw/node fails in the edge next runtime (since the runtime is running a minimal version of node I guess). However, that's another issue though. It's still great to know that it's possible |
Beta Was this translation helpful? Give feedback.
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: