testability
БесплатноБез исполняемых скриптовНе проверенMake features testable by design. Testing pyramid from fast (local) to slow (UI). Expose APIs securely for testing.
Об этом скилле
What I Do
Ensure every feature you build is testable from the start. This skill teaches:
- Testing pyramid (fast → slow)
- API exposure patterns for testability
- Local testing setup
- Integration with staging tests
- When to use each testing layer
Core Philosophy
"If you can't test it locally, you can't test it."
Every feature should be testable at multiple levels. Design for testability, don't bolt it on later.
Testing Pyramid
From fastest (run constantly) to slowest (run occasionally):
▲
/U\ UI Tests (E2E)
/ I \ - Browser automation
/-----\ - Run on staging only
/ API \ API/Integration Tests
/ TESTS \ - tRPC procedures
/-----------\ - Can run locally
/ UNIT \ Unit Tests
/ TESTS \ - Pure functions
/------------------\ - Fastest, run always
| Layer | Speed | Where | When to Use |
|---|---|---|---|
| Unit | <1s | Local | Pure logic, utils, calculations |
| API/Integration | 1-10s | Local + CI | tRPC, DB operations, business logic |
| Staging | 30s-2m | Vercel preview | Full flow verification |
| UI/E2E | 2-5m | Staging only | Critical user journeys |
Layer 1: Unit Tests (Fastest)
When to Use
- Pure functions with no side effects
- Calculations, formatting, validation
- Business logic that doesn't touch DB/APIs
Pattern
// packages/web/src/lib/utils/calculate-fee.ts
export function calculateFee(amount: number, feePercent: number): number {
return amount * (feePercent / 100);
}
// packages/web/src/lib/utils/calculate-fee.test.ts
import { describe, it, expect } from 'vitest';
import { calculateFee } from './calculate-fee';
describe('calculateFee', () => {
it('calculates 1% fee correctly', () => {
expect(calculateFee(1000, 1)).toBe(10);
});
it('handles zero amount', () => {
expect(calculateFee(0, 5)).toBe(0);
});
});
Running Unit Tests
cd packages/web
pnpm test # Run all tests (watch mode)
pnpm test -- --run # Run once and exit
pnpm test:watch # Watch mode
pnpm test -- --run --grep "fee" # Filter by name
Repo note:
@zero-finance/webVitest discovers tests underpackages/web/src/test/**/*.test.ts. Put new tests there (or update Vitest config) so they get picked up.
Layer 2: API/Integration Tests
When to Use
- tRPC procedures
- Database operations
- External API integrations (mocked)
- Business logic with dependencies
Pattern: Testing tRPC Procedures
// packages/web/src/server/routers/earn/get-balance.test.ts
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { createTestContext } from '@/test/context';
import { earnRouter } from './index';
describe('earn.getBalance', () => {
let ctx: ReturnType<typeof createTestContext>;
beforeEach(() => {
ctx = createTestContext({
user: { privyDid: 'test-user-did' },
workspaceId: 'test-workspace-id',
});
});
it('returns balance for valid user', async () => {
const caller = earnRouter.createCaller(ctx);
const result = await caller.getBalance({ chainId: 8453 });
expect(result).toHaveProperty('balance');
expect(typeof result.balance).toBe('string');
});
});
Pattern: Mocking External Services
// Mock Privy
vi.mock('@privy-io/server-auth', () => ({
PrivyClient: vi.fn().mockImplementation(() => ({
getUser: vi.fn().mockResolvedValue({ id: 'test-user' }),
})),
}));
// Mock Database
vi.mock('@/db', () => ({
db: {
query: {
userSafes: {
findFirst: vi.fn().mockResolvedValue({
safeAddress: '0x1234...',
chainId: 8453,
}),
},
},
},
}));
Test Database Setup
For tests that need a real database:
// packages/web/src/test/setup-db.ts
import { drizzle } from 'drizzle-orm/neon-http';
import { neon } from '@neondatabase/serverless';
export async function createTestDb() {
// Use a test-specific database
const sql = neon(process.env.TEST_DATABASE_URL!);
return drizzle(sql);
}
Layer 3: Staging Tests (Vercel Preview)
When to Use
- Full end-to-end flows
- Features that involve multiple services
- UI changes that need visual verification
- Flows that can't be mocked locally
Workflow
# 1. Push your branch
git push -u origin feat/my-feature
# 2. Wait for deployment
LATEST=$(vercel ls --scope prologe 2>/dev/null | head -1)
vercel inspect "$LATEST" --scope prologe --wait --timeout 5m
# 3. Test on preview URL
# Use Chrome MCP or manual testing
Integration wit
Установить testability в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл testability?
Make features testable by design. Testing pyramid from fast (local) to slow (UI). Expose APIs securely for testing.
Как установить скилл testability?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл testability запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
frontend-design
Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making…
от Anthropicwebapp-testing
Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing…
от Anthropicbrand-guidelines
Applies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand…
от Anthropicweb-artifacts-builder
Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui). Use…
от Anthropic