Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

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от 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

  1. 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.
  2. Test procedures in isolation first -- Use createCallerFactory to invoke router procedures directly without HTTP overhead. This enables fast, reliable unit tests.
  3. Test middleware independently -- Middleware often contains critical auth and validation logic. Test middleware functions in isolation before testing the full procedure chain.
  4. Integration tests for the full stack -- After unit testing individual procedures, add integration tests that exercise the HTTP adapter, serialization, and error handling.
  5. Mock context, not procedures -- When testing a procedure, provide a controlled context object (user session, database connection) rather than mocking the procedure itself.
  6. Subscription testing requires real transports -- WebSocket subscriptions cannot be tested with simple callers. Use real WebSocket connections or test the subscription logic separately.
  7. React hook testing with providers -- tRPC React hooks require proper provider setup. Use createTRPCReact with a test client and QueryClientProvider for 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
Полный SKILL.md на GitHub

Установить 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), без исполняемых скриптов.

Похожие скиллы

Сравнить tRPC Testing с