Skip to content

Instantly share code, notes, and snippets.

@solace
Last active February 19, 2025 12:11
Show Gist options
  • Save solace/c0263f4007fb9ac9443f2e73affa13e7 to your computer and use it in GitHub Desktop.
Save solace/c0263f4007fb9ac9443f2e73affa13e7 to your computer and use it in GitHub Desktop.
next.js 15 playwright testmode onFetch wrapper
const AUTH_USER_ENDPOINT = /\/auth\/v1\/user/;
export const userRemote = (email: string) => ({
method: 'GET',
route: AUTH_USER_ENDPOINT,
response: {
data: {
id: 'uuid',
email,
role: 'authenticated',
user_metadata: {
email,
},
app_metadata: {
provider: 'email',
}
},
});
export const userRemoteNotFound = {
method: 'GET',
route: AUTH_USER_ENDPOINT,
response: {data: null, options: {status: 404}},
};
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';
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment