freshyo/apps/admin-ui/tests/mocks/api.ts
2026-10-01 00:33:03 +05:30

73 lines
2.3 KiB
TypeScript

/**
* Network-layer mocks for the admin-ui tests.
*
* All tRPC traffic goes through `global.fetch` (httpBatchLink). The registry
* resolves each batched procedure by name; anything not supplied resolves to
* `null`, and tests override with the exact shape they assert against. Tests
* that need to prove "nothing was called" use tests/mocks/procedures.ts.
*/
import { StorageService } from 'common-ui/src/services/StorageService'
import { StorageServiceCasual } from 'common-ui/src/services/StorageServiceCasual'
import { parseTrpcUrl } from './procedures'
const jsonResponse = (body: unknown) => ({
ok: true,
status: 200,
statusText: 'OK',
headers: new Map(),
url: '',
json: async () => body,
text: async () => JSON.stringify(body),
clone: () => jsonResponse(body),
})
export interface ApiMockOptions {
/**
* Procedure registry: name -> data, or (input) => data. Unlisted procedures
* resolve to null.
*/
procedures?: Record<string, unknown | ((input: unknown) => unknown)>
/** The essentialConsts-style consts payload, if a screen reads it. */
consts?: unknown
}
export function setupApiMocks(opts: ApiMockOptions = {}) {
const resolveProcedure = (name: string, input: unknown): unknown => {
const override = opts.procedures?.[name]
if (override !== undefined) {
return typeof override === 'function'
? (override as (value: unknown) => unknown)(input)
: override
}
return null
}
const fetchMock = jest.fn(
async (url: string, options?: { method?: string; body?: unknown }) => {
const target = String(url)
const calls = parseTrpcUrl(target, options?.body)
if (calls.length === 0) {
// Presigned S3 uploads PUT straight to a URL.
if (options?.method === 'PUT') return jsonResponse({})
throw new Error(`[tests] unmocked fetch: ${url}`)
}
const batch = calls.map(({ name, input }) => ({
result: { data: resolveProcedure(name, input) },
}))
return jsonResponse(batch)
}
)
;(global as unknown as { fetch: unknown }).fetch = fetchMock
return { fetchMock }
}
/** Clear the in-memory auth token + any casual storage. Call from beforeEach. */
export async function resetStorage() {
await StorageService.clearAll(['jwt_token'])
await StorageServiceCasual.clearAll([])
}