import type {NextFixture} from 'next/dist/experimental/testmode/playwright'; export default function mockFetch( next: NextFixture, handlers: {method: string; route: RegExp; response: {data: any; options?: any}}[] ) { next.onFetch((request: Request) => { for (let i = 0; i < handlers.length; i++) { if ( request.method === handlers[i].method && request.url.match(handlers[i].route) ) { return new Response(JSON.stringify(handlers[i].response.data), { headers: { 'Content-Type': 'application/json', }, ...(handlers[i].response.options ?? {}), }); } } // EXCLUDED_URLS contains a regex of paths I would allow through such as Google Analytics or logging services if (request.url.match(EXCLUDED_URLS)) { return 'continue'; } console.log(`No handler for ${request.method} ${request.url.split('?')[0]}`); return 'abort'; }); }