Files
gold_land_user/test/helpers/fetchMock.ts
T

51 lines
1.8 KiB
TypeScript
Raw Normal View History

export type MockResponse = {
status: number
body?: unknown
delayMs?: number
}
declare global {
// eslint-disable-next-line no-var
var routeHandlers: Map<string, (init?: RequestInit) => MockResponse | Promise<MockResponse>>
}
export function installFetchMock() {
globalThis.routeHandlers = new Map()
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input.toString()
const path = url.replace(/^https?:\/\/[^/]+/, '').replace(/^\/api/, '') || url
const handler = globalThis.routeHandlers.get(path)
if (!handler) {
return new Response(JSON.stringify({ error: 'not found' }), { status: 404 })
}
const spec = await handler(init)
if (spec.delayMs && spec.delayMs > 0) {
await new Promise((r) => setTimeout(r, spec.delayMs))
}
return new Response(JSON.stringify(spec.body ?? {}), {
status: spec.status,
headers: { 'Content-Type': 'application/json' },
})
}) as typeof fetch
}
export async function resetAppTestState() {
const { resetSessionTrackingForTests } = await import('../../src/api/authSession')
const { resetUserStateRevisionForTests, resetMeMutationSyncForTests } = await import(
'../../src/api/sync'
)
const { resetMeMutationQueueForTests } = await import('../../src/api/meMutationQueue')
const { resetCatalogFetchSyncForTests } = await import('../../src/api/catalogFetchSync')
const { setAuthToken } = await import('../../src/api/token')
const { resetAppBootstrap } = await import('../../src/api/bootstrapState')
resetSessionTrackingForTests()
resetUserStateRevisionForTests()
resetMeMutationSyncForTests()
resetMeMutationQueueForTests()
resetCatalogFetchSyncForTests()
resetAppBootstrap()
setAuthToken(null)
}