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

test-gen — скилл для Claude Code: что делает и как установить

Скилл test-gen генерирует и прогоняет тесты под существующий фреймворк проекта с проверкой типичных сценариев, краевых случаев и ошибок.

MIT ★ 937 обновлён 2026-10-29

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add SethGammon/Citadel
/plugin install citadel@citadel-local
Открыть на GitHub

Что делает test-gen

Скилл анализирует конфигурационные файлы вроде jest.config.* или pytest.ini, считывает стиль импортов и структуру проверок. Для указанного файла, функции или целой директории агент строит тесты в трёх плоскостях: позитивный сценарий, граничные значения и обработка ошибок.

Внешние зависимости вроде HTTP-клиентов или баз данных мокаются, но внутренние утилиты и тестируемый модуль остаются настоящими. Главное правило процесса — исходный код проекта менять запрещено. Если тест выявил баг в коде, скилл помечает проверку как .skip или .todo и выносит дефект в итоговый отчёт. На исправление сгенерированных тестов даётся максимум три итерации.

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

  • написать первый набор тестов для модуля или отдельной функции
  • проверить граничные значения и ошибки без ручного составления тест-кейсов
  • найти скрытые баги в кодовой базе без изменения исходников
  • подогнать новые тесты под стиль уже настроенного тестового раннера

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

  • /test-gen src/auth/session.ts
  • /test-gen src/auth/session.ts:validateToken
  • Напиши тесты для всех модулей в папке src/utils/

Как установить test-gen

1Через маркетплейс плагинов

/plugin marketplace add SethGammon/Citadel
/plugin install citadel@citadel-local

Команда ставит плагин citadel целиком, со всеми его скиллами

2Через Skills CLI (Vercel)

npx skills add SethGammon/Citadel --skill test-gen -a claude-code

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

~/.claude/skills/test-gen/SKILL.md

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

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

Вопросы о test-gen

Как установить test-gen в Claude Code?

Выполните по очереди две команды в консоли: /plugin marketplace add SethGammon/Citadel, затем /plugin install citadel@citadel-local.

Что делает test-gen?

Генерирует тесты под ваш тестовый фреймворк, проверяет позитивные ветки, граничные условия и ошибки, а затем сам запускает тест-сьют и устраняет сбои.

Что происходит, если тест находит баг в коде?

Агент не правит рабочий код ради зелёных тестов: он оставляет проверку с пометкой .skip, описывает проблему и добавляет найденный баг в блок Source Issues Found.

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

SKILL.md · MIT
---
name: test-gen
license: MIT
description: Generate and verify tests — happy path, edge cases, error paths — using the project's own framework and patterns
user-invocable: true
trigger_keywords:
  - /test-gen
  - generate tests
  - write tests
  - add tests
  - test
---

# Identity

You write tests that run on the first try. Match the project's test style exactly — framework, assertion library, describe/it nesting, import patterns. Generate happy path, edge cases, and error paths, then run and fix failures. Never ship a red suite. Mock only external services, I/O, and time.

## Orientation

**Use when:** generating initial test coverage for a module -- happy path, edge cases, and error paths from scratch.
**Don't use when:** tests already exist and need updating (use /review or /improve); writing integration tests across services (use /marshal with an explicit test plan).

# Orientation

**Input**: A test target — one of:
- A file path (`/test-gen src/auth/session.ts`)
- A specific function (`/test-gen src/auth/session.ts:validateToken`)
- A directory (`/test-gen src/utils/`) — generates tests for each exported module

**Output**: One or more test files that pass, covering happy path, edge cases, and error paths for every exported function/class in scope.

**Constraints**:
- Tests must run and pass before delivery — no "these should work" handoffs
- Maximum 3 fix iterations per test file. If a test still fails after 3 attempts, mark it as `.skip` with a comment explaining why, and move on
- Never modify the source code to make tests pass. If the source has a bug, write the test to document expected behavior and mark it with `.todo` or `.skip` plus a note

## Protocol

## Step 1 — Detect test framework

Check config files (`jest.config.*`, `vitest.config.*`, `pytest.ini`, etc.), `package.json` devDependencies, and the nearest existing test file. Capture: framework, runner command, file naming, file location, import style, assertion style, mocking style, describe/it nesting. If no test infrastructure exists, recommend a framework and ask the user to install it first.

## Step 2 — Analyze the target

For each exported function/class/method, extract: signature, branches (if/switch/ternary/try/catch/early return), dependencies (internal vs external), side effects, error conditions. Map every branch to at least one test case before writing code.

## Step 3 — Generate tests

Write the test file following the project's exact patterns. Organize into three sections per function:

### Happy Path
- Primary use case with typical, valid input; multiple input shapes if behavior differs
- Verify return value AND expected side effects

### Edge Cases
- Boundary values: 0, 1, -1, empty string/array/object, MAX_SAFE_INTEGER, very long strings
- Null/undefined for every parameter that could receive them (only if reachable given the type system)
- Collection: empty, single element, duplicates, very large
- String: whitespace-only, unicode, special characters
- Concurrent access if function manages shared state

### Error Paths
- Invalid input (at untyped boundaries), out-of-range values, malformed data
- Dependency failures: throws, returns null, times out, unexpected data
- State precondition violations: wrong method order, closed/disposed resources
- Verify error type/message, not just that it throws

### Mocking rules
- Mock: HTTP clients, DB connections, file system, timers, random number generators
- Do NOT mock: internal utilities, data transformations, pure functions, the module under test
- Prefer fakes over mocks when available. Reset mocks in `beforeEach`/`afterEach`. Type mocks to match the real interface.

## Step 4 — Write the test file

One file per source file. Group with `describe` blocks per function/class. Descriptive test names state behavior (`"returns empty array when input is empty"`). Shared fixtures in `beforeEach`. Each test independent. Extract helpers for setups over 15 lines.

## Step 5 — Run and verify

Run only the generated file. For each failure: determine root cause — test bug (fix the test, never change expected value to match wrong behavior) or source bug (`.skip` with `// SKIP: source bug — {description}`). Up to 3 iterations. After 3 failed attempts: `.skip` with `// SKIP: could not resolve after 3 attempts — {last error}`.

## Step 6 — Coverage check

If a coverage tool is configured, run it for the target file. Add tests for meaningful uncovered branches. Skip if no coverage tool exists — do not install one.

## Contextual Gates

**Disclosure:** "Generating tests for [target]. Creates new test files; no existing files modified."
**Reversibility:** green — creates new test files only; delete the generated test files to undo
**Trust gates:**
- Any: generate tests for any target file or directory

## Quality Gates

1. All tests pass — final run with `node scripts/run-with-timeout.js 300 <test-cmd>`. Skips must have documented reasons.
2. No snapshot-only tests — every test asserts specific behavior.
3. No implementation coupling — tests don't break on internal refactors. Don't assert on internal variable values, call counts, or execution order.
4. No test interdependence — each test runnable in isolation.
5. Mocks are minimal — only external boundaries. Internal functions: remove the mock and test through real code.
6. Test names are self-documenting — the describe/it tree explains behavior without reading source.

## Exit Protocol

Deliver:

```
## Tests Generated: {target}

**Framework**: {detected framework}
**Test file**: {path to generated test file}
**Results**: {N passed}, {N skipped} of {N total}

### Coverage
- {function/method name}: {branches covered} / {total branches}
- ...

### Skipped Tests
- {test name}: {reason}
- ...
(or "None — all tests pass.")
```

If any tests were skipped due to source bugs, call them out clearly — these are findings, not failures of test generation:

```
### Source Issues Found
- **{file}:{line}**: {description of the bug the test exposed}
```

Do not offer to fix source bugs unless asked. The tests are the deliverable.

© SethGammon · MIT · SethGammon/Citadel

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

Все скиллы по теме «Тесты и QA» →
generate-tests davila7 Команда generate-tests создаёт готовый файл тестов для указанного компонента или файла. Команда определяет тестовый фреймворк проекта и генерирует проверки по паттерну AAA. CX Codex +1 12 378установок test-coverage-improver OneWave-AI Скилл test-coverage-improver находит пробелы в покрытии тестами и генерирует недостающие тесты для критичных участков кода. CX Codex +1 312установок test-guard amElnagdy Скилл test-guard для Claude Code и других агентов проверяет сгенерированные тесты на избыточность, лишние моки и совпадение с логикой проекта перед коммитом. Работает с pytest, Jest, Vitest, Go и PHPUnit. CX Codex +1 4 400установок test-writer-fixer Community Плагин test-writer-fixer для Claude Code, который запускает юнит-тесты после правок в коде, пишет недостающие и чинит упавшие. Срабатывает автоматически при рефакторинге, новых фичах или багфиксах. ★ 2 003звёзд репо parallel-test-fixing spencerpauly Скилл parallel-test-fixing распределяет упавшие файлы тестов между параллельными субагентами, чтобы исправлять ошибки независимо. Он нужен при поломке сразу нескольких тестовых файлов. CX Codex +1 455установок test-audit mblode Скилл test-audit для Claude Code, Cursor, Codex и других агентов, который вырезает малоценные тесты из сьюта до заданной цели, сохраняя покрытие. Запускается как точечный аудит папки или кампания на весь репозиторий с числовым таргетом. CX Codex +1 283установок

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

Весь набор →
decision-map Скилл decision-map превращает расплывчатую идею в карту вопросов, которую можно продолжать между сессиями. Он помогает разобраться в неизвестном до того, как работа станет задачей на сборку. CX Codex +1 ★ 937звёзд репо archon Субагент archon, который ведёт большую задачу по фазам: разбивает направление на шаги, передаёт их другим агентам и хранит состояние кампании между запусками. CX Codex ★ 937звёзд репо loop Скилл loop для Claude Code и Codex, который запускает действие несколько раз подряд и проверяет результат каждый раз, пока не пройдёт проверка или не кончатся попытки. CX Codex +1 ★ 937звёзд репо marshal Скилл marshal для Claude Code разбирает задачу, собирает контекст из кода и памяти и связывает скиллы в цепочку. Работает за одну сессию и спрашивает, только если не может продолжить. CX Codex +1 ★ 937звёзд репо design Скилл design собирает дизайн-манифест из стилей проекта или ответов на вопросы. Хук после правок отмечает отклонения в CSS и компонентах. CX Codex +1 ★ 937звёзд репо live-preview Скилл live-preview делает скриншоты компонентов в процессе сборки, а не по готовности. Ловит регрессии вёрстки и невидимые блоки до того, как они уйдут дальше. CX Codex +1 ★ 937звёзд репо architect Скилл architect превращает PRD или описание задачи в архитектурный план с деревом файлов, моделью данных и фазами сборки. CX Codex +1 ★ 937звёзд репо cost Скилл cost показывает расход токенов и стоимость сессий, кампаний и периодов. Помогает понять, куда уходит бюджет и как меняется темп расходов. CX Codex +1 ★ 937звёзд репо

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

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