freshyo/apps/user-ui/tests/mocks/procedures.ts
2026-09-26 13:41:46 +05:30

131 lines
3.9 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. They are structural (the mock is a jest.fn), so no jest
* types leak into call sites.
*/
export interface ProcedureCall {
name: string
input: unknown
}
/** The fetch mock shape these helpers need. */
export interface FetchMockLike {
mock: { calls: unknown[][] }
}
const MARKER = '/api/trpc/'
/** Parse the batch input envelope (`{ "0": { json } }`) from a string. */
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 }>
}
}
/**
* The batch input map is `{ "0": <input> }`. If a transformer is configured the
* value is a superjson envelope (`{ json, meta }`); this project sends the raw
* input, so fall back to the value itself.
*/
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.
* Queries carry the input in the query string; mutations (POST) carry it in the
* request body, so the body is accepted too.
*/
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)
})
}
/** Calls to one procedure. */
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
}
/** Convenience: the single input when a procedure is called exactly once. */
export function procedureInput(
fetchMock: FetchMockLike,
name: string
): unknown {
return lastProcedureInput(fetchMock, name)
}