- Remove unused @trpc/tanstack-react-query dependency - Document renderWithProviders tRPC provider omission (boundary constraint) - Implement deep merge in defineFactory (preserves nested sibling keys) - Document httpBatchLink<any> rationale in mock-trpc.ts - Align core-testing's own vitest.config with safety defaults (mockReset, unstubGlobals) - Add createMockTrpcClient usage example to AGENTS.md Reviewer: superpowers:code-reviewer (Task 1 of Plan 7). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
33 lines
1.4 KiB
TypeScript
33 lines
1.4 KiB
TypeScript
import { createTRPCClient, httpBatchLink } from "@trpc/client";
|
|
import superjson from "superjson";
|
|
import type { AnyTRPCRouter } from "@trpc/server";
|
|
|
|
// Returns a tRPC client whose fetch is a stub honouring the provided mocks.
|
|
// Mocks are keyed by procedure path ("blog.articleBySlug") returning the
|
|
// raw response body.
|
|
export function createMockTrpcClient<TRouter extends AnyTRPCRouter>(
|
|
mocks: Record<string, unknown> = {},
|
|
) {
|
|
const fetchStub: typeof fetch = async (input) => {
|
|
const url = typeof input === "string" ? input : (input as Request).url;
|
|
const path = new URL(url, "http://mock").pathname.replace(/^\/api\/trpc\//, "");
|
|
const result = mocks[path];
|
|
if (result === undefined) {
|
|
return new Response(JSON.stringify([{ error: { code: -32603, message: `No mock for ${path}` } }]), { status: 200 });
|
|
}
|
|
return new Response(JSON.stringify([{ result: { data: superjson.serialize(result) } }]), { status: 200 });
|
|
};
|
|
|
|
// httpBatchLink<TRouter> requires a conditional TransformerOptions<TRouter> that
|
|
// depends on whether the router uses a transformer; making this generic-friendly
|
|
// without parameterizing twice requires <any> here.
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const link = httpBatchLink<any>({
|
|
url: "http://mock/api/trpc",
|
|
transformer: superjson,
|
|
fetch: fetchStub,
|
|
});
|
|
|
|
return createTRPCClient<TRouter>({ links: [link] });
|
|
}
|