Last active
February 19, 2025 12:11
-
-
Save solace/c0263f4007fb9ac9443f2e73affa13e7 to your computer and use it in GitHub Desktop.
next.js 15 playwright testmode onFetch wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}}, | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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