К основному содержанию
скилл CX Codex

testing-principles — скилл для Claude Code

Скилл testing-principles для Claude Code задаёт правила выбора и оформления тестов независимо от языка стека. Включается при написании новых тестов, проверке их качества и выборе между unit-, integration- и E2E-уровнями.

MIT ★ 720 обновлён 2026-11-11

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add shinpr/claude-code-workflows --skill testing-principles -a claude-code
Открыть на GitHub

Что делает testing-principles

Скилл формулирует правила тестирования поведения на публичных границах системы: интеграционных и сквозных E2E-тестах для пользовательских сценариев и юнит-тестах для ветвлений или парсинга. Каждое утверждение о поведении закрепляется ровно за одним тестом, чтобы исключить дублирование и хрупкие проверки деталей реализации. Покрытие кода рассматривается как диагностический сигнал, а не самоцель.

Внутри собраны требования к структуре Arrange-Act-Assert, изоляции состояния и очистке после каждого прогона. Правила требуют мокать только прямой внешний ввод-вывод через существующие адаптеры приложения, оставляя внутреннюю бизнес-логику настоящей. Для репозиториев и миграций базы данных скилл требует проверки на реальной СУБД проекта, а не на моках.

В скилле также описан обязательный регрессионный тест для каждого воспроизводимого бага и создание слепка поведения перед правками легаси-кода.

Какие задачи решает

  • выбрать между сквозным E2E, интеграционным или юнит-тестом для новой функциональности
  • выстроить структуру тестов по схеме Arrange-Act-Assert без проверки приватных методов
  • ограничить моки внешним вводом-выводом и сохранить настоящую бизнес-логику
  • подтвердить совместимость запросов и миграций на реальной СУБД проекта
  • зафиксировать регрессионный тест при исправлении найденного бага

Примеры запросов агенту

  • Проверь этот PR и подскажи, какие тесты избыточны, а где не хватает сквозной проверки
  • Напиши интеграционный тест для авторизации по принципам из testing-principles
  • Помоги составить регрессионный тест для бага с расчётом скидки в корзине

Как установить testing-principles

1Через Skills CLI (Vercel)

npx skills add shinpr/claude-code-workflows --skill testing-principles -a claude-code

2Вручную: положить файлы

~/.claude/skills/testing-principles/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/testing-principles/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о testing-principles

Как установить testing-principles в Claude Code?

Выполните команду npx skills add shinpr/claude-code-workflows --skill testing-principles -a claude-code. Также можно сохранить файл навыка в каталог ~/.claude/skills/testing-principles/SKILL.md.

Для чего нужен скилл testing-principles?

Он задаёт стандарты проектирования проверок, помогая ИИ-агенту выбирать правильный уровень между юнит-, интеграционными и сквозными тестами. Скилл запрещает тестировать детали реализации и дублировать проверки одних и тех же правил на разных уровнях.

Когда скилл требует настоящую базу данных вместо моков?

Моки допустимы, если обращение к данным служит лишь фоновой зависимостью сценария. Проверка запросов, логики репозиториев, ограничений схемы и миграций должна проходить на реальной СУБД проекта или её одобренном эквиваленте.

Исходный текст

SKILL.md · MIT
---
name: testing-principles
description: Language-agnostic testing principles for choosing which tests a change needs, test quality, and proof ownership, including frontend and browser E2E tests. Use when writing tests, deciding test scope, or reviewing test quality.
---

# Language-Agnostic Testing Principles

Tests here guarantee accepted behavior, and the next agent reads every existing test as a requirement to preserve. A brittle, duplicated, or implementation-shaped test therefore becomes a false requirement: it gets worked around, and the workaround leaves debt in the implementation. Keep the set of tests whose proof is worth its maintenance.

## Test Selection

- Prove accepted behavior by default through integration and E2E tests at the boundary users and callers observe. Add a unit test for logic whose cases one representative boundary test cannot prove, such as calculations, parsing, or branching rules.
- Each behavioral claim is owned by one test: such logic by its unit test, other behavior by the test at the narrowest integration or E2E boundary where it is observable. A test at a wider boundary or in a variant (viewport, device, role) proves what that boundary or variant adds, such as wiring, mapping, persistence, rendering, or navigation, and keeps at most one representative case of a rule owned elsewhere.
- Determine the required proof boundary from the accepted outcome before minimizing tests. An outcome delivered through an application or service entry point includes the relevant production composition, such as routing, providers, state ownership or adapters. An isolated component test or a test-built substitute composition does not prove that wiring. Reuse proof that traverses it, or select a test that will; choose the harness by what it must observe, not by component count or a lane quota. A disconnected action, lost state update or broken transition can remain invisible to tests below that boundary. Explicitly component-scoped outcomes retain their component boundary.
- Treat coverage as a diagnostic signal for finding untested areas, not a target; any CI threshold is the project's config, not a quality goal in itself.
- Use project-configured speed budgets when present. Otherwise investigate test speed only when observed feedback or CI cost is material to the current outcome; retain slower tests when their proof boundary requires it.

## Test Design Rules

- Structure each test as Arrange, one Act, and Assert; multiple assertions may prove one behavior.
- Follow the repository's test naming convention and name the condition and observable outcome.
- Exercise behavior through a public or integration boundary. Assertions verify return values, outputs, errors, or state changes rather than private implementation.
- Use independently derived literal, property, approved snapshot, or fixture expectations. An implementation-derived oracle cannot detect the same implementation defect.
- Keep each test's expected outcome unconditional. Table-driven or property-based cases are acceptable when each case is reported distinctly and uses an independent oracle.
- Cover accepted boundary and error behavior; derive cases from the contract instead of adding generic edge-case permutations.
- Each test creates and cleans up its own state, passes in isolation and any order, and controls time or randomness that affects its result.
- Keep tests executable. Fix or remove tests that no longer describe accepted behavior; restore tests disabled only to bypass a failure.

## Mock and Boundary Rules

- Mock direct external I/O boundaries; keep internal business logic and the boundary under test real.
- Use the existing application-owned adapter as the mock boundary. Introduce an adapter only when external I/O, an unstable contract, or required substitution cannot be controlled through the current design.
- Keep mock behavior limited to the contract needed by the test.

## Data Layer Testing

Mock-based tests are sufficient when data access is only a dependency of the behavior under test. Verify against the project's real database engine or its accepted equivalent when the subject is a query, repository implementation, schema constraint, or migration compatibility. Resolve the test environment from repository configuration; when no representative environment exists and adding one is outside the approved work, report the missing verification decision.

Cross-check data-access code against the schema source named in the Design Doc or repository configuration. Schema-source verification is required to prove table, column, type, constraint, or dialect compatibility; successful mocks prove behavior only at the mocked boundary.

## Verification Requirements

### Capability Probe Postconditions

A capability probe passes when it uses the consumer's boundary and asserts the exact property that consumer needs. Command success, import success, or object existence is setup evidence.

## Test Organization

Follow the repository's established test paths, runner routing, and naming. When establishing an approved new convention, separate test types only when their setup, runner, or environment differs.

## Regression Testing

- Add a regression test for every reproducible behavior bug fix. When executable reproduction is impossible, record the reason and the alternative static, contract, or environment evidence that prevents recurrence.
- Before behavior-preserving changes to uncharacterized legacy code, establish passing characterization evidence and rerun it after the change.

## References

- [references/frontend.md](references/frontend.md): read when writing, changing, or reviewing component, hook, or UI integration tests
- [references/e2e.md](references/e2e.md): read when writing, changing, or reviewing browser E2E tests

© shinpr · MIT · shinpr/claude-code-workflows

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

Все скиллы по теме «Тесты и QA» →
unit-testing-framework aj-geddes Скилл unit-testing-framework для Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI и OpenCode: пишет юнит-тесты по паттерну AAA с моками и покрытием критических путей. CX Codex +1 633установок testing-expert PCL Team Скилл testing-expert задаёт агенту правила написания тестов: структура AAA, независимые кейсы, моки и граничные случаи. Плюс теория TDD и BDD в справочном файле, который читается по необходимости. CX Codex +1 206установок testing sangrokjung Правило testing задаёт строгий TDD-процесс для Claude Code: планку покрытия от 80%, три уровня проверок и сценарии Playwright. CX Codex +1 ★ 880звёзд репо principle-test-behavior-not-implementation backnotprop Скилл principle-test-behavior-not-implementation для Claude Code задаёт правила проверки кода через внешний интерфейс. Агент применяет его при написании, изменении или ревизии тестов. CX Codex +1 10 200установок test-driven-development addyosmani Скилл test-driven-development для Claude Code ведёт разработку через цикл «красный — зелёный — рефакторинг». Он подключается при добавлении логики, исправлении ошибки и изменении поведения кода. CX Codex +1 78 300установок project-testing aiskillstore Скилл project-testing с готовыми паттернами и фиксчами для unit-, integration- и E2E-тестов. Помогает писать изолированные тесты быстро, по одному стандарту, без хардкода и flaky-тестов. CX Codex +1 1установок

Из того же набора43

Весь набор →
external-resource-context Скилл external-resource-context фиксирует пути и методы доступа к внешним схемам API, макетам, IaC и хранилищам секретов. Помогает агенту работать с ресурсами вне репозитория. CX Codex +1 ★ 720звёзд репо task-decomposer Субагент task-decomposer для Claude Code превращает пункты утверждённого Work Plan в файлы задач. Создаёт отдельный файл для каждой задачи. CX Codex ★ 720звёзд репо acceptance-test-generator Субагент acceptance-test-generator для Claude Code создаёт каркасы интеграционных и E2E-тестов на основе критериев приёмки из Design Doc. Запускается при проектировании тестов или по фразе test skeleton. CX Codex ★ 720звёзд репо requirement-analyzer Субагент requirement-analyzer собирает границы изменений и факторы затрат в кодовой базе для подтверждения требований перед разработкой. CX Codex ★ 720звёзд репо llm-friendly-context Скилл llm-friendly-context для Claude Code правит промпты, хендоффы и отчёты, чтобы следующий агент видел входы, шаги и критерии успеха. CX Codex +1 ★ 720звёзд репо requirement-convergence Скилл requirement-convergence для Claude Code отделяет целевой результат изменений от предложенных требований и фиксирует исключения пользователя. Включается на этапе сбора требований до проектирования архитектуры. CX Codex +1 ★ 720звёзд репо work-planner Субагент work-planner для Claude Code превращает утверждённые Design Doc в план реализации с задачами, зависимостями и проверками. Запускается при запросе плана работ или планирования задач. CX Codex ★ 720звёзд репо typescript-rules Набор правил для фронтенд-разработки на React и TypeScript: типобезопасность, устройство компонентов, владение состоянием и обработка ошибок. CX Codex +1 ★ 720звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой