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

122 lines
3.4 KiB
TypeScript

/**
* Assert which tRPC procedures a screen called, and with what input.
*
* Every tRPC call goes through `global.fetch` (httpBatchLink), whose URL is
* `/api/trpc/<name>[,<name>...]?batch=1&input=<json>`. The input param is an
* object keyed by the batch index: `{ "0": { json: <input> }, ... }`.
*
* tests/mocks/api.ts installs the fetch stub; pass its returned `fetchMock` to
* these helpers.
*/
export interface ProcedureCall {
name: string
input: unknown
}
export interface FetchMockLike {
mock: { calls: unknown[][] }
}
const MARKER = '/api/trpc/'
const parseInputEnvelope = (raw: string | undefined) => {
if (!raw) return {} as Record<string, { json?: unknown }>
try {
return JSON.parse(raw) as Record<string, { json?: unknown }>
} catch {
return {} as Record<string, { json?: unknown }>
}
}
const unwrapInput = (entry: unknown): unknown => {
if (
entry != null &&
typeof entry === 'object' &&
'json' in entry &&
'meta' in entry
) {
return (entry as { json: unknown }).json
}
return entry
}
/** Split a tRPC request URL into one entry per batched procedure. */
export function parseTrpcUrl(url: string, body?: unknown): ProcedureCall[] {
const target = String(url)
const at = target.indexOf(MARKER)
if (at === -1) return []
const rest = target.slice(at + MARKER.length)
const queryAt = rest.indexOf('?')
const path = queryAt === -1 ? rest : rest.slice(0, queryAt)
const query = queryAt === -1 ? '' : rest.slice(queryAt + 1)
const names = path.split(',').filter(Boolean)
let inputsByIndex: Record<string, { json?: unknown }> = {}
const match = /(?:^|&)input=([^&]*)/.exec(query)
if (match) {
inputsByIndex = parseInputEnvelope(decodeURIComponent(match[1]))
} else if (typeof body === 'string') {
inputsByIndex = parseInputEnvelope(body)
}
return names.map((name, index) => ({
name,
input: unwrapInput(inputsByIndex[String(index)]),
}))
}
/** Every procedure call recorded by the fetch mock, in order. */
export function calledProcedures(fetchMock: FetchMockLike): ProcedureCall[] {
return fetchMock.mock.calls.flatMap(([url, options]) => {
const body = (options as { body?: unknown } | undefined)?.body
return parseTrpcUrl(String(url), body)
})
}
export function procedureCalls(
fetchMock: FetchMockLike,
name: string
): ProcedureCall[] {
return calledProcedures(fetchMock).filter((call) => call.name === name)
}
/** Assert a procedure was called (optionally exactly `times`). */
export function expectProcedureCalled(
fetchMock: FetchMockLike,
name: string,
options: { times?: number } = {}
): ProcedureCall[] {
const calls = procedureCalls(fetchMock, name)
if (options.times != null) {
expect(calls).toHaveLength(options.times)
} else {
expect(calls.length).toBeGreaterThan(0)
}
return calls
}
/** Input of the most recent call to a procedure (undefined if never called). */
export function lastProcedureInput(
fetchMock: FetchMockLike,
name: string
): unknown {
const calls = procedureCalls(fetchMock, name)
return calls.length === 0 ? undefined : calls[calls.length - 1].input
}
export function procedureInput(
fetchMock: FetchMockLike,
name: string
): unknown {
return lastProcedureInput(fetchMock, name)
}
/** Number of calls to a procedure. */
export function procCount(fetchMock: FetchMockLike, name: string): number {
return procedureCalls(fetchMock, name).length
}