freshyo/apps/admin-ui/tests/mocks/trpc-client.ts
2026-10-20 00:31:05 +05:30

447 lines
13 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Manual mock for `@/src/trpc-client`.
*
* Every backend procedure is a keyed entry in a registry. Tests set the outcome
* (`success` / `error` / `pending`), the payload, or a dynamic `impl`, then the
* page under test reads it through the same `trpc.<path>.useQuery/useMutation`
* surface it uses in production.
*
* Call recording powers the catalogue's "assert the procedure name and exact
* input" rule: `lastProcedureInput`, `procedureMutationCalls`, ...
*/
import * as React from 'react'
import { defaultProcedures } from './trpc-defaults'
export type ProcedureMode = 'success' | 'error' | 'pending'
export interface ProcedureConfig {
mode?: ProcedureMode
data?: any
error?: unknown
impl?: (input: any) => any
}
interface ProcedureRecord {
config: ProcedureConfig
queryCalls: any[]
mutationCalls: any[]
invalidations: any[]
}
const procedures = new Map<string, ProcedureRecord>()
let version = 0
const listeners = new Set<() => void>()
function bump() {
version += 1
listeners.forEach((listener) => listener())
}
function subscribe(listener: () => void) {
listeners.add(listener)
return () => {
listeners.delete(listener)
}
}
const getVersion = () => version
function record(path: string): ProcedureRecord {
let entry = procedures.get(path)
if (!entry) {
entry = { config: {}, queryCalls: [], mutationCalls: [], invalidations: [] }
procedures.set(path, entry)
}
return entry
}
export function setProcedure(path: string, config: ProcedureConfig) {
const entry = record(path)
entry.config = { ...entry.config, ...config }
bump()
}
export function setProcedures(map: Record<string, ProcedureConfig>) {
Object.entries(map).forEach(([path, config]) => {
const entry = record(path)
entry.config = { ...entry.config, ...config }
})
bump()
}
export function clearProcedure(path: string) {
const entry = procedures.get(path)
if (entry) entry.config = {}
bump()
}
export function getProcedureConfig(path: string): ProcedureConfig {
return procedures.get(path)?.config ?? {}
}
export function seedDefaultProcedures() {
setProcedures(defaultProcedures)
}
export function resetTrpcMocks() {
procedures.clear()
version = 0
listeners.clear()
seedDefaultProcedures()
}
export function procedureQueryCalls(path: string): any[] {
return [...(procedures.get(path)?.queryCalls ?? [])]
}
export function procedureMutationCalls(path: string): any[] {
return [...(procedures.get(path)?.mutationCalls ?? [])]
}
export function procedureInvalidations(path: string): any[] {
return [...(procedures.get(path)?.invalidations ?? [])]
}
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]
if (all.length === 0) return undefined
return all[all.length - 1]
}
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)
}
function resolveData(config: ProcedureConfig, input: any): any {
if (config.impl) return config.impl(input)
return config.data
}
function useQueryImpl(path: string, input: any, options: any = {}) {
React.useSyncExternalStore(subscribe, getVersion, getVersion)
const enabled = options?.enabled !== false
const entry = record(path)
const inputKey = JSON.stringify(input ?? null)
React.useEffect(() => {
if (enabled) entry.queryCalls.push(input)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [enabled, inputKey])
const config = entry.config
const mode = enabled ? config.mode ?? 'success' : 'success'
const isPending = enabled && mode === 'pending'
const isError = enabled && mode === 'error'
const error = isError ? config.error ?? new Error(`[trpc mock] ${path} failed`) : null
let data: any = undefined
if (enabled && !isPending && !isError) {
data = resolveData(config, input)
if (data === undefined) data = options?.placeholderData
if (options?.select && data !== undefined && data !== null) data = options.select(data)
}
return {
data,
error,
status: isPending ? 'pending' : isError ? 'error' : 'success',
isLoading: isPending,
isPending,
isFetching: isPending,
isRefetching: false,
isSuccess: enabled && !isPending && !isError,
isError,
isFetched: enabled && !isPending,
isFetchedAfterMount: enabled && !isPending,
isPlaceholderData: false,
isStale: false,
failureCount: isError ? 1 : 0,
failureReason: error,
dataUpdatedAt: 0,
errorUpdatedAt: 0,
refetch: jest.fn(async () => ({ data, error })),
}
}
function useInfiniteQueryImpl(path: string, input: any, options: any = {}) {
const base = useQueryImpl(path, input, options)
const pages = base.data && Array.isArray((base.data as any).pages) ? (base.data as any).pages : []
return {
...base,
data: base.data ? { pages, pageParams: pages.map((_: any, index: number) => index) } : undefined,
fetchNextPage: jest.fn(async () => undefined),
fetchPreviousPage: jest.fn(async () => undefined),
hasNextPage: false,
hasPreviousPage: false,
isFetchingNextPage: false,
isFetchingPreviousPage: false,
}
}
function useMutationImpl(path: string, options: any = {}) {
React.useSyncExternalStore(subscribe, getVersion, getVersion)
const entry = record(path)
const optionsRef = React.useRef(options)
optionsRef.current = options
const [state, setState] = React.useState<{
status: 'idle' | 'pending' | 'success' | 'error'
data?: any
error?: unknown
}>({ status: 'idle' })
const run = React.useCallback(
async (input: any) => {
entry.mutationCalls.push(input)
const current = optionsRef.current ?? {}
const config = entry.config
const mode = config.mode ?? 'success'
setState({ status: 'pending' })
if (mode === 'pending') {
return new Promise<any>(() => {
/* never settles */
})
}
if (mode === 'error') {
const error = config.error ?? new Error(`[trpc mock] ${path} failed`)
setState({ status: 'error', error })
try {
current.onError?.(error, input, undefined)
} catch {
/* ignore */
}
try {
current.onSettled?.(undefined, error, input, undefined)
} catch {
/* ignore */
}
throw error
}
const data = resolveData(config, input)
setState({ status: 'success', data })
try {
current.onSuccess?.(data, input, undefined)
} catch {
/* ignore */
}
try {
current.onSettled?.(data, null, input, undefined)
} catch {
/* ignore */
}
return data
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[path]
)
const mutate = React.useCallback(
(input: any, mutateOptions?: any) => {
run(input).then(
(data) => mutateOptions?.onSuccess?.(data, input, undefined),
(error) => mutateOptions?.onError?.(error, input, undefined)
)
},
[run]
)
return {
mutate,
mutateAsync: run,
reset: () => setState({ status: 'idle' }),
data: state.data,
error: state.error,
status: state.status,
isPending: state.status === 'pending',
isLoading: state.status === 'pending',
isError: state.status === 'error',
isSuccess: state.status === 'success',
isIdle: state.status === 'idle',
failureCount: 0,
variables: undefined,
}
}
function queryNode(path: string): any {
return {
useQuery: (input?: any, options?: any) => useQueryImpl(path, input, options),
useInfiniteQuery: (input?: any, options?: any) => useInfiniteQueryImpl(path, input, options),
useMutation: (options?: any) => useMutationImpl(path, options),
}
}
function procedureNode(path: string): any {
return new Proxy(
{},
{
get(_target, prop) {
if (typeof prop !== 'string') return undefined
if (prop === 'useQuery' || prop === 'useInfiniteQuery' || prop === 'useMutation') {
return queryNode(path)[prop]
}
const next = path ? `${path}.${prop}` : prop
return procedureNode(next)
},
}
)
}
function recordInvalidation(path: string) {
const entry = record(path)
const spy = jest.fn(() => {
entry.invalidations.push({ path })
return Promise.resolve()
})
return spy
}
function utilsNode(path: string): any {
return new Proxy(
{},
{
get(_target, prop) {
if (typeof prop !== 'string') return undefined
switch (prop) {
case 'invalidate':
return recordInvalidation(path)
case 'refetch':
return jest.fn(async () => ({ data: resolveData(getProcedureConfig(path), undefined) }))
case 'fetch':
return jest.fn(async (input?: any) => resolveData(getProcedureConfig(path), input))
case 'setData':
return jest.fn()
case 'getData':
return jest.fn(() => resolveData(getProcedureConfig(path), undefined))
case 'cancel':
return jest.fn(async () => undefined)
case 'remove':
return jest.fn()
case 'setInfiniteData':
return jest.fn()
case 'getInfiniteData':
return jest.fn(() => undefined)
case 'invalidateQueries':
return jest.fn(async () => undefined)
default:
return utilsNode(path ? `${path}.${prop}` : prop)
}
},
}
)
}
const utilsProxy: any = new Proxy(
{},
{
get(_target, prop) {
if (typeof prop !== 'string') return undefined
if (prop === 'invalidate') return recordInvalidation('root')
if (prop === 'refetch') return jest.fn(async () => undefined)
if (prop === 'setData') return jest.fn()
if (prop === 'getData') return jest.fn(() => undefined)
if (prop === 'cancel') return jest.fn(async () => undefined)
if (prop === 'remove') return jest.fn()
if (prop === 'invalidateQueries') return jest.fn(async () => undefined)
return utilsNode(prop)
},
}
)
const TrpcProvider = ({ children }: { children?: React.ReactNode }) =>
React.createElement(React.Fragment, null, children)
function makeRootProxy(): any {
return new Proxy(
{},
{
get(_target, prop) {
if (typeof prop !== 'string') return undefined
switch (prop) {
case 'Provider':
return TrpcProvider
case 'createClient':
return () => ({ __mockTrpcClient: true })
case 'useUtils':
return () => utilsProxy
case 'useContext':
return () => ({})
default:
return procedureNode(prop)
}
},
}
)
}
export const trpc: any = makeRootProxy()
function clientNode(path: string): any {
return new Proxy(
{},
{
get(_target, prop) {
if (typeof prop !== 'string') return undefined
switch (prop) {
case 'query':
return async (input?: any) => {
const entry = record(path)
entry.queryCalls.push(input)
const config = entry.config
if ((config.mode ?? 'success') === 'error') {
throw config.error ?? new Error(`[trpc mock] ${path} failed`)
}
return resolveData(config, input)
}
case 'mutate':
return async (input?: any) => {
const entry = record(path)
entry.mutationCalls.push(input)
const config = entry.config
if ((config.mode ?? 'success') === 'error') {
throw config.error ?? new Error(`[trpc mock] ${path} failed`)
}
return resolveData(config, input)
}
case 'subscribe':
return () => ({ unsubscribe: jest.fn() })
default:
return clientNode(path ? `${path}.${prop}` : prop)
}
},
}
)
}
export const trpcClient: any = clientNode('')
// Seed on import so components always have data unless a test overrides it.
seedDefaultProcedures()
export default { trpc, trpcClient }