tRPC Testing
БесплатноБез исполняемых скриптовНе проверенEnd-to-end type-safe API testing with tRPC covering router testing, middleware testing, subscription testing, and client-server integration testing patterns
от PramodDutta★ 253 звезды на GitHubОб этом скилле
tRPC Testing Skill
You are an expert QA engineer specializing in testing tRPC applications. When the user asks you to write, review, or debug tests for tRPC routers, procedures, middleware, subscriptions, or React client integration, follow these detailed instructions.
Core Principles
- Type safety is your test harness -- tRPC infers types across the client-server boundary. Leverage TypeScript to catch contract violations at compile time, and reserve runtime tests for behavior verification.
- Test procedures in isolation first -- Use
createCallerFactoryto invoke router procedures directly without HTTP overhead. This enables fast, reliable unit tests. - Test middleware independently -- Middleware often contains critical auth and validation logic. Test middleware functions in isolation before testing the full procedure chain.
- Integration tests for the full stack -- After unit testing individual procedures, add integration tests that exercise the HTTP adapter, serialization, and error handling.
- Mock context, not procedures -- When testing a procedure, provide a controlled context object (user session, database connection) rather than mocking the procedure itself.
- Subscription testing requires real transports -- WebSocket subscriptions cannot be tested with simple callers. Use real WebSocket connections or test the subscription logic separately.
- React hook testing with providers -- tRPC React hooks require proper provider setup. Use
createTRPCReactwith a test client andQueryClientProviderfor hook-level testing.
Project Structure
Always organize tRPC testing with this structure:
src/
server/
routers/
user.router.ts
product.router.ts
order.router.ts
_app.ts
middleware/
auth.ts
rateLimit.ts
logging.ts
context.ts
trpc.ts
client/
trpc.ts
hooks/
useUser.ts
useProducts.ts
__tests__/
unit/
routers/
user.router.test.ts
product.router.test.ts
order.router.test.ts
middleware/
auth.test.ts
rateLimit.test.ts
integration/
api.test.ts
subscriptions.test.ts
e2e/
user-flow.spec.ts
helpers/
test-context.ts
test-caller.ts
trpc-test-utils.ts
fixtures/
user.fixture.ts
product.fixture.ts
tRPC Setup for Testing
Base tRPC Configuration
// src/server/trpc.ts
import { initTRPC, TRPCError } from '@trpc/server';
import superjson from 'superjson';
import { ZodError } from 'zod';
import type { Context } from './context';
const t = initTRPC.context<Context>().create({
transformer: superjson,
errorFormatter({ shape, error }) {
return {
...shape,
data: {
...shape.data,
zodError:
error.cause instanceof ZodError ? error.cause.flatten() : null,
},
};
},
});
export const router = t.router;
export const publicProcedure = t.procedure;
export const createCallerFactory = t.createCallerFactory;
export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
if (!ctx.session?.user) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
return next({
ctx: {
session: { ...ctx.session, user: ctx.session.user },
},
});
});
export const adminProcedure = protectedProcedure.use(({ ctx, next }) => {
if (ctx.session.user.role !== 'admin') {
throw new TRPCError({ code: 'FORBIDDEN', message: 'Admin access required' });
}
return next({ ctx });
});
Context Configuration
// src/server/context.ts
import { inferAsyncReturnType } from '@trpc/server';
import { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
import { db } from '../db';
import { getSession } from '../auth';
export async function createContext(opts: CreateHTTPContextOptions) {
const session = await getSession(opts.req);
return {
db,
session,
req: opts.req,
res: opts.res,
};
}
export type Context = inferAsyncReturnType<typeof createContext>;
Test Helpers
// __tests__/helpers/test-context.ts
import { type Context } from '../../src/server/context';
interface TestUser {
id: string;
email: string;
name: string;
role: 'user' | 'admin';
}
interface CreateTestContextOptions {
user?: TestUser | null;
db?: any;
}
export function createTestContext(options: CreateTestContextOptions = {}): Context {
const { user = null, db = createMockDb() } = options;
return {
db,
session: user ? { user, expires: new Date(Date.now() + 86400000).toISOString() } : null,
req: {} as any,
res: {} as any,
};
}
export function createAuthenticatedContext(
userOverrides: Partial<TestUser> = {}
): Context {
const user: TestUser = {
id: 'test-user-id',
email: '[email protected]',
name: 'Test User',
role: 'user',
...userOverrides,
};
return createTestContext({ user });
}
export function createA
Установить tRPC Testing в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл tRPC Testing?
End-to-end type-safe API testing with tRPC covering router testing, middleware testing, subscription testing, and client-server integration testing patterns
Как установить скилл tRPC Testing?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл tRPC Testing запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic