/* eslint-disable @typescript-eslint/no-explicit-any */ /** * tRPC test harness — procedure registry + network-level mock. * * The app's REAL `@/src/trpc-client` now runs in tests (real `httpBatchLink` + * real React Query). This module only fakes the **network response**: * * real hook -> real tRPC client -> global fetch (this mock) -> registry * * `installTrpcNetworkMock()` replaces `global.fetch`. It parses the batch * request the client builds: * * GET /api/trpc/a.b,c.d?batch=1&input={"0":…,"1":…} * POST /api/trpc/a.b?batch=1 body {"0":…} * * and answers with the tRPC batch envelope, using the per-procedure registry: * * setProcedure('user.order.getOrders', { data: ORDERS_RESPONSE }) * setProcedure('user.auth.login', { mode: 'error', error: new Error('boom') }) * setProcedure('user.auth.login', { mode: 'pending' }) * setProcedure('user.auth.login', { impl: (input) => … }) * * Call recording (`lastProcedureInput`, `procedureMutationCalls`, …) is filled * from the same requests, so assertions keep working. */ import { defaultProcedures } from './trpc-defaults' export type ProcedureMode = 'success' | 'error' | 'pending' export interface ProcedureConfig { mode?: ProcedureMode data?: any error?: unknown /** Optional tRPC error code override (default derived from `error.status`). */ errorCode?: string impl?: (input: any) => any } interface ProcedureRecord { config: ProcedureConfig queryCalls: any[] mutationCalls: any[] } export interface NetworkCall { path: string input: any kind: 'query' | 'mutation' authorization: string | null } const procedures = new Map() const invalidations: string[] = [] const networkCalls: NetworkCall[] = [] let rawFetchHandler: ((url: string, init: any) => Promise) | null = null let installed = false function record(path: string): ProcedureRecord { let entry = procedures.get(path) if (!entry) { entry = { config: {}, queryCalls: [], mutationCalls: [] } procedures.set(path, entry) } return entry } export function setProcedure(path: string, config: ProcedureConfig) { const entry = record(path) entry.config = { ...entry.config, ...config } } export function setProcedures(map: Record) { Object.entries(map).forEach(([path, config]) => { const entry = record(path) entry.config = { ...entry.config, ...config } }) } export function clearProcedure(path: string) { const entry = procedures.get(path) if (entry) entry.config = {} } export function getProcedureConfig(path: string): ProcedureConfig { return procedures.get(path)?.config ?? {} } export function seedDefaultProcedures() { setProcedures(defaultProcedures) } export function resetTrpcMocks() { procedures.clear() invalidations.length = 0 networkCalls.length = 0 rawFetchHandler = null seedDefaultProcedures() } export function procedureQueryCalls(path: string): any[] { return [...(procedures.get(path)?.queryCalls ?? [])] } export function procedureMutationCalls(path: string): any[] { return [...(procedures.get(path)?.mutationCalls ?? [])] } /** Invalidation keys recorded from the real `queryClient.invalidateQueries`. */ export function procedureInvalidations(path: string): string[] { if (path === 'root') return invalidations.filter((entry) => entry === 'root') return invalidations.filter((entry) => entry === path) } export function procedureCallCount(path: string): number { const entry = procedures.get(path) if (!entry) return 0 return entry.queryCalls.length + entry.mutationCalls.length } export function lastProcedureInput(path: string): any { const entry = procedures.get(path) if (!entry) return undefined const all = [...entry.queryCalls, ...entry.mutationCalls] return all.length ? all[all.length - 1] : undefined } export function lastMutationInput(path: string): any { const calls = procedures.get(path)?.mutationCalls ?? [] return calls.length ? calls[calls.length - 1] : undefined } export function expectProcedureCalled(path: string, times?: number) { const count = procedureCallCount(path) if (times === undefined) expect(count).toBeGreaterThan(0) else expect(count).toBe(times) } export function expectNoProcedureCall(path: string) { expect(procedureCallCount(path)).toBe(0) } /** Every tRPC request the real client made (flattened across batches). */ export function recordedNetworkCalls(): NetworkCall[] { return [...networkCalls] } export function lastNetworkCall(path?: string): NetworkCall | undefined { const calls = path ? networkCalls.filter((call) => call.path === path) : networkCalls return calls[calls.length - 1] } /** Override the response for non-tRPC fetches (uploads, etc.). */ export function setRawFetchHandler(handler: ((url: string, init: any) => Promise) | null) { rawFetchHandler = handler } function recordInvalidationKey(queryKey: unknown) { if (queryKey === undefined) { invalidations.push('root') return } if (Array.isArray(queryKey) && Array.isArray(queryKey[0])) { invalidations.push((queryKey[0] as unknown[]).map(String).join('.')) return } if (typeof queryKey === 'string') invalidations.push(queryKey) } /** Called by the test QueryClient wrapper. */ export function recordQueryInvalidation(filters: any) { recordInvalidationKey(filters?.queryKey) } function resolveData(config: ProcedureConfig, input: any): any { if (config.impl) return config.impl(input) return config.data } const HTTP_STATUS_CODES: Record = { 400: 'BAD_REQUEST', 401: 'UNAUTHORIZED', 403: 'FORBIDDEN', 404: 'NOT_FOUND', 405: 'METHOD_NOT_SUPPORTED', 409: 'CONFLICT', 422: 'UNPROCESSABLE_CONTENT', 429: 'TOO_MANY_REQUESTS', 500: 'INTERNAL_SERVER_ERROR', } function errorEntry(path: string, error: unknown, codeOverride?: string) { const message = error instanceof Error ? error.message : String(error ?? 'Request failed') const status = Number( (error as { status?: number })?.status ?? (error as { httpStatus?: number })?.httpStatus ?? 500 ) const httpStatus = Number.isFinite(status) && status >= 400 ? status : 500 const code = codeOverride ?? (error as { code?: string })?.code ?? HTTP_STATUS_CODES[httpStatus] ?? 'INTERNAL_SERVER_ERROR' return { error: { message, code: -32603, json: { message, code: -32603, data: { code, httpStatus, path }, }, }, } } function parseRequest(url: string, init: any) { const parsed = new URL(url) const marker = '/api/trpc/' const index = parsed.pathname.indexOf(marker) const rawPaths = index >= 0 ? parsed.pathname.slice(index + marker.length) : '' const paths = rawPaths.split(',').filter(Boolean) const method = String(init?.method ?? 'GET').toUpperCase() let inputs: Record = {} if (method === 'GET') { const raw = parsed.searchParams.get('input') if (raw) inputs = JSON.parse(raw) } else if (typeof init?.body === 'string' && init.body.length > 0) { inputs = JSON.parse(init.body) } const headers = init?.headers ?? {} const authorization = (headers as any).Authorization ?? (headers as any).authorization ?? null return { paths, method, inputs, authorization } } async function handleTrpcRequest(url: string, init: any): Promise { const { paths, method, inputs, authorization } = parseRequest(url, init) const kind: 'query' | 'mutation' = method === 'GET' ? 'query' : 'mutation' // Record every call first: a pending request is still a real request, and // tests assert "exactly one request was made" even while the hook is loading. const inputsByPath = paths.map((path, index) => { const input = inputs[String(index)] const entry = record(path) if (kind === 'query') entry.queryCalls.push(input) else entry.mutationCalls.push(input) networkCalls.push({ path, input, kind, authorization }) return { path, input, entry } }) // `mode: 'pending'` keeps the whole batch (and therefore the hook) loading. if (paths.some((path) => getProcedureConfig(path).mode === 'pending')) { return new Promise(() => { /* never settles */ }) } const entries = inputsByPath.map(({ path, input, entry }) => { const config = entry.config if ((config.mode ?? 'success') === 'error') { return errorEntry(path, config.error ?? new Error(`[trpc mock] ${path} failed`), config.errorCode) } return { result: { data: resolveData(config, input) } } }) return new Response(JSON.stringify(entries), { status: 200, headers: { 'content-type': 'application/json' }, }) } /** * Replace `global.fetch` with the tRPC-aware mock. Called once from * `tests/setup.ts`; the real client still builds the request. */ export function installTrpcNetworkMock() { if (installed) return installed = true ;(global as any).fetch = jest.fn(async (input: any, init: any = {}) => { const url = typeof input === 'string' ? input : input?.url ?? String(input) if (!url.includes('/api/trpc')) { if (rawFetchHandler) return rawFetchHandler(url, init) return new Response(JSON.stringify({ ok: true }), { status: 200, headers: { 'content-type': 'application/json' }, }) } return handleTrpcRequest(url, init) }) } /** True when `fetch` is the harness mock (useful in assertions). */ export function isTrpcNetworkMockInstalled(): boolean { return installed }