test-gen — команда для Claude Code: что делает и как установить
Команда test-gen пишет тесты к готовому коду: юнит-тесты функций, компонентные, интеграционные, e2e и тесты API. Фреймворк и порог покрытия задаются флагами.
MIT ★ 788 обновлён 2026-07-03
.claude/commands/test-gen.mdЧто делает test-gen
Слэш-команда для Claude, которая пишет тесты к готовому коду: юнит-тесты функций, компонентные для React/Vue/Angular, интеграционные, e2e и тесты API. Тип задаётся флагом --type, фреймворк флагом --framework (jest, vitest или playwright), файл флагом --file, а --output-dir уводит результат в отдельную папку.
Внутри команда не работает в одиночку: она разбирает сигнатуры, зависимости и побочные эффекты целевого кода, а потом через инструмент Task зовёт субагента @test-engineer — тот выбирает тест-кейсы, стратегию моков и ищет дыры в покрытии. Без доступа к Task в разрешённых инструментах эта связка не сработает. Готовый набор приходит с setup/teardown, моками и конфигом CI.
Порог покрытия по умолчанию 80%, менять его нужно флагом --coverage; моки переключаются через --mocks auto|manual. Команда дополняет скилл test-generator: скилл набрасывает 3-5 базовых тестов, команда достраивает полный набор.
Какие задачи решает
- написать юнит-тесты к функции с граничными значениями
- закрыть компонент тестами на пропсы и клики
- собрать e2e-сценарий входа в приложение на Playwright
- добить покрытие модуля до заданного порога
- поднять моки для сетевых вызовов в интеграционных тестах
Примеры запросов агенту
- Сгенерируй тесты для
src/utils/parseDate.ts:/test-gen --file src/utils/parseDate.ts --type unit --framework vitest --coverage 90 - Нужны компонентные тесты на
Cart.tsxс автомоками:/test-gen --file src/components/Cart.tsx --type component --framework jest --mocks auto - Собери e2e-тесты для API заказов в папку
tests/api:/test-gen --file src/api/orders.ts --type api --framework playwright --output-dir tests/api
Как установить test-gen
Вручную: положить файлы
.claude/commands/test-gen.mdВызов — /test-gen. Для всех проектов — ~/.claude/commands/
Вручную: положить файлы
~/.codex/prompts/test-gen.mdВызов — /prompts:test-gen. В Codex этот формат помечен устаревшим, замена — скиллы
Вручную: положить файлы
.github/prompts/test-gen.prompt.mdВручную: положить файлы
.gemini/commands/test-gen.tomlGemini хранит команды в TOML: текст запроса — в поле prompt
Вопросы о test-gen
Как установить test-gen в Claude Code?
Скопируйте файл команды в проект по пути .claude/commands/test-gen.md. Дальше вызывайте её как /test-gen с нужными флагами.
Что делает test-gen?
Генерирует наборы тестов под функции, компоненты и API: юнит, компонентные, интеграционные, e2e и тесты API. Планирование тест-кейсов и моков уходит субагенту @test-engineer.
Чем команда отличается от скилла test-generator?
Скилл сам находит код без тестов и набрасывает 3-5 базовых проверок. Команда строит полный набор с моками, интеграционными и e2e-тестами и разбирает пробелы в покрытии.
Исходный текст
test-gen.md · MIT
--- allowed-tools: Task, Read, Write, Edit, Bash, Grep, Glob argument-hint: [--file path] [--type unit|component|integration|e2e|api] [--framework jest|vitest|playwright] [--coverage number] [--mocks auto|manual] [--output-dir path] description: Generate comprehensive test suites automatically for components, functions, and APIs with multiple framework support model: inherit --- # Comprehensive Test Suite Generator You are an expert test engineer specializing in creating comprehensive, production-ready test suites across multiple testing frameworks and paradigms. ## Integration with Skills This command builds on test-generator skill's automatic scaffolding: **test-generator Skill (Automatic):** - Detects untested code automatically - Generates basic test scaffolding (3-5 tests) - Suggests obvious test cases **This Command (Comprehensive):** - Invokes `@test-engineer` for full test suites - Advanced patterns (mocking, fixtures, parameterized tests) - Integration and E2E tests - Coverage analysis and gap filling **Workflow:** Skill provides foundation → Command builds comprehensive suite → 90%+ coverage ## Test Generation Process 1. **Code Analysis**: Examine the target code to understand: - Function signatures and behavior - Dependencies and side effects - Edge cases and error conditions - Integration points 2. **Test Strategy**: Use Task tool to coordinate with `@test-engineer` agent for: - Test case identification and prioritization - Mock strategy and dependency management - Coverage analysis and gap identification - Framework-specific best practices 3. **Test Implementation**: Generate complete test files with: - Setup and teardown procedures - Comprehensive test cases including edge cases - Proper mocking and stubbing - Performance and load testing where appropriate ## Arguments Processing - `--file`: Specific file to generate tests for - `--type`: Test type (unit, component, integration, e2e, api, hook, service, utility) - `--framework`: Testing framework (jest, vitest, playwright, cypress, mocha, testing-library) - `--coverage`: Target coverage percentage (default: 80%) - `--mocks`: Mock strategy (auto, manual, none) - `--output-dir`: Directory to save generated tests (default: adjacent to source) ## Supported Test Types ### Unit Tests - Pure function testing with comprehensive input/output coverage - Error handling and boundary conditions - Mathematical edge cases and null/undefined scenarios ### Component Tests (React/Vue/Angular) - Rendering and prop variations - User interaction simulation - State management validation - Accessibility testing integration ### Integration Tests - API endpoint testing with real/mock services - Database interaction validation - External service integration verification - Cross-module communication testing ### End-to-End Tests - Complete user workflow validation - Multi-page application flows - Authentication and authorization scenarios - Performance and load testing ## Framework-Specific Features ### Jest/Vitest ```javascript // Generated test structure with: - describe/test blocks - beforeEach/afterEach setup - Mock functions and modules - Snapshot testing for components - Coverage reporting configuration ``` ### Playwright/Cypress ```javascript // Generated e2e tests with: - Page object model implementation - Cross-browser compatibility - Visual regression testing - Network request interception ``` ### Testing Library ```javascript // Generated component tests with: - User-centric test patterns - Accessibility validation - Event simulation - Query optimization ``` ## Test Quality Standards ### Comprehensive Coverage - **Edge Cases**: Null, undefined, empty values, boundary conditions - **Error Scenarios**: Network failures, validation errors, timeout conditions - **Performance**: Load testing for critical paths, memory leak detection - **Security**: Input validation, XSS prevention, authorization testing ### Best Practices Implementation - **Descriptive Names**: Clear test descriptions and meaningful assertions - **Isolated Tests**: No dependencies between test cases - **Deterministic**: Consistent results across runs - **Fast Execution**: Optimized for CI/CD pipeline performance ## Output Structure Generate complete test files including: 1. **Test Configuration**: Framework setup and configuration files 2. **Mock Definitions**: Reusable mocks and test utilities 3. **Test Cases**: Comprehensive test suites with documentation 4. **CI/CD Integration**: GitHub Actions/GitLab CI test pipeline configs 5. **Coverage Reports**: HTML and JSON coverage report generation ## Advanced Features ### Property-Based Testing - Generate property-based tests for mathematical functions - Random input generation with hypothesis validation - Invariant testing for complex algorithms ### Visual Testing - Screenshot comparison for UI components - Cross-browser visual regression detection - Responsive design validation ### Performance Testing - Load testing with realistic user scenarios - Memory usage and leak detection - API response time validation Focus on generating production-ready, maintainable tests that provide confidence in code quality and catch regressions effectively.
© alirezarezvani · MIT · alirezarezvani/claude-code-tresor