write-tests
БесплатноБез исполняемых скриптовНе проверенWrite tests following project conventions. Use when adding new tests or modifying existing ones.
от getsentry★ 77 звёзд на GitHubОб этом скилле
Write Tests Skill
Write tests using Vitest. Tests are colocated next to source files.
Structure
src/lib/utils.ts
src/lib/utils.test.ts # colocated
src/app/api/stats/route.ts
src/app/api/stats/route.test.ts
src/test-utils/
├── setup.ts # global setup (PGlite, MSW, auth mock)
├── msw-handlers.ts # external API mocks
└── auth.ts # auth test helpers
Auth Testing
Auth is globally mocked. Use helpers to control auth state:
import { mockAuthenticated, mockUnauthenticated } from '@/test-utils/auth';
it('returns 401 when unauthenticated', async () => {
await mockUnauthenticated();
const response = await GET(new Request('http://localhost/api/foo'));
expect(response.status).toBe(401);
});
it('returns data when authenticated', async () => {
await mockAuthenticated(); // uses default test user
// or with overrides:
await mockAuthenticated({ email: '[email protected]' });
const response = await GET(new Request('http://localhost/api/foo'));
expect(response.status).toBe(200);
});
Default test user: [email protected] / Test User
Database Testing
Uses PGlite (in-memory PostgreSQL). No Docker required.
- Schema pushed automatically on boot
- Each test runs in a transaction that rolls back
- Use
insertUsageRecordfrom@/lib/queriesto seed data
import { insertUsageRecord, getOverallStats } from '@/lib/queries';
beforeEach(async () => {
await insertUsageRecord({
date: '2025-01-01',
email: '[email protected]',
tool: 'claude_code',
model: 'sonnet-4',
rawModel: 'claude-sonnet-4-20250514',
inputTokens: 1000,
outputTokens: 500,
cacheWriteTokens: 0,
cacheReadTokens: 0,
cost: 0.01,
});
});
Running Tests
pnpm test # run all
pnpm test:watch # watch mode
Key Rules
- Colocate tests next to source (
foo.ts→foo.test.ts) - Use
mockAuthenticated()/mockUnauthenticated()for auth - Use
insertUsageRecordfor seeding database - External APIs mocked via MSW in
src/test-utils/msw-handlers.ts
CRITICAL: Auth Tests Required
Every protected route MUST have an auth test. This is non-negotiable.
Session-Authenticated Routes
Routes using getSession() must verify 401 on unauthenticated requests:
it('returns 401 for unauthenticated requests', async () => {
await mockUnauthenticated();
const response = await GET(new Request('http://localhost/api/your-route'));
expect(response.status).toBe(401);
});
Cron Routes
Routes using CRON_SECRET must verify auth:
beforeEach(() => {
vi.stubEnv('CRON_SECRET', 'test-secret');
});
it('returns 401 without authorization header', async () => {
const response = await GET(new Request('http://localhost/api/cron/your-route'));
expect(response.status).toBe(401);
});
it('returns 401 with invalid authorization', async () => {
const response = await GET(
new Request('http://localhost/api/cron/your-route', {
headers: { Authorization: 'Bearer wrong-secret' },
})
);
expect(response.status).toBe(401);
});
Webhook Routes
Routes with signature verification must test invalid signatures:
it('returns 401 without signature', async () => {
const response = await POST(
new Request('http://localhost/api/webhooks/github', {
method: 'POST',
body: '{}',
})
);
expect(response.status).toBe(401);
});
it('returns 401 with invalid signature', async () => {
const response = await POST(
new Request('http://localhost/api/webhooks/github', {
method: 'POST',
body: '{}',
headers: { 'x-hub-signature-256': 'sha256=invalid' },
})
);
expect(response.status).toBe(401);
});
When adding a new route, always ask: "What auth does this route require?" and add the corresponding auth test.
Установить write-tests в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobEditWriteBashFAQ
Что делает скилл write-tests?
Write tests following project conventions. Use when adding new tests or modifying existing ones.
Как установить скилл write-tests?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл write-tests запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic