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

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

Скилл generate-tests пишет тесты для файла, модуля или компонента, сначала определяя фреймворк и конвенции проекта.

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

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

Что делает generate-tests

Скилл разбирает проект до того, как писать код: ищет конфиг фреймворка (jest.config.*, vitest.config.*, playwright.config.*, pytest.ini, go.mod, Cargo.toml), смотрит на существующие *.test.* и *.spec.*, находит общие хелперы и читает скрипт test в package.json. Стиль файлов, импортов и ассертов он берёт у проекта.

Дальше разбор целевого файла: экспорты, типы, внешние зависимости, побочные эффекты, ветки с ошибками. План делится на юнит-тесты, интеграционные и краевые случаи, моки ставятся только на внешние вызовы. После генерации скилл прогоняет набор и добивает пробелы с оглядкой на branch coverage: ориентиры по покрытию идут от 90%+ для критичной логики до 60%+ для конфигурации.

Первый шаг не пропускается. Пока скилл не нашёл фреймворк и конвенции, тестов он не пишет, поэтому в репозитории без тестового конфига сначала придётся сказать, чем вы тестируете.

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

  • дописать юнит-тесты на экспортированные функции модуля
  • закрыть ветки с ошибками и catch, до которых не доходили руки
  • поднять покрытие перед релизом
  • подставить моки вместо реальных API и базы
  • завести первый тестовый набор в проекте без тестов

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

  • Сгенерируй тесты для src/lib/parseDate.ts, фреймворк определи сам
  • Доведи покрытие billing/invoice.ts: нужны кейсы с ошибками, пустыми и null-значениями
  • Напиши первый набор тестов для компонента UserCard, запросы к API замокай

Как установить generate-tests

1Через Skills CLI (Vercel)

npx skills add coco-research/coco --skill generate-tests -a claude-code

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

~/.claude/skills/generate-tests/SKILL.md

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

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

Вопросы о generate-tests

Как установить generate-tests в Claude Code?

Выполните npx skills add coco-research/coco --skill generate-tests -a claude-code. Скилл окажется по пути ~/.claude/skills/generate-tests/SKILL.md.

Что делает generate-tests?

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

С какими фреймворками он работает?

Распознаёт Jest, Vitest, Cypress, Playwright, pytest, Go testing и Rust #[cfg(test)], а в компонентных тестах следует схемам React Testing Library, Vue Test Utils, Angular TestBed и Supertest.

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

SKILL.md · MIT
---
name: generate-tests
description: "Use when asked to generate tests for a file, module or component, to raise coverage, or to bootstrap a suite for untested code. Detects the project's test framework and conventions first, then writes unit, integration and edge-case tests."
domain: engineering
supports: [claude-code, cursor, codex, generic]
version: 0.1.0
---

# Generate Tests — Comprehensive Test Suite Generator

Generate complete test coverage for any file, component, or module. Covers unit tests, integration tests, edge cases, error handling, and mocking — adapted to whatever testing framework the project uses.

**Use when**: you want tests generated for a file or component, need to improve test coverage, want edge case coverage, need mocks for external dependencies, or want to bootstrap a test suite for untested code.

---

## When This Skill Is Activated

Follow every step below. Do NOT generate tests without first analyzing the project's testing setup and the target code.

---

## Step 1: Detect the Testing Setup

Before writing any tests, discover the project's testing conventions:

1. **Find the test framework** — Check `package.json` (dependencies/scripts), or config files:
   - `jest.config.*` / `jest` key in `package.json` → Jest
   - `vitest.config.*` → Vitest
   - `cypress.config.*` → Cypress
   - `playwright.config.*` → Playwright
   - `pytest.ini` / `pyproject.toml` [tool.pytest] → pytest
   - `go.mod` → Go testing
   - `Cargo.toml` → Rust (#[cfg(test)])

2. **Find existing test files** — Search for `*.test.*`, `*.spec.*`, `test_*.py`, `*_test.go` to understand naming conventions and patterns already in use.

3. **Check for test utilities** — Look for shared helpers, factories, custom matchers, or mock setups the project already provides (e.g., `test/utils.ts`, `__mocks__/`, `conftest.py`).

4. **Check the test script** — Read the `test` script in `package.json` (or equivalent) to understand how tests are run, what flags are used, and what coverage tool is configured.

**Match the project's existing conventions exactly.** File naming, import style, assertion style, describe/it vs test, etc.

---

## Step 2: Analyze the Target Code

Read the file or component the user wants tested. Identify:

- All exported functions, classes, methods, and components
- Input types and return types (or infer them)
- External dependencies (API calls, database, file system, third-party libs)
- Side effects (mutations, network calls, timers, DOM manipulation)
- Error paths (throw statements, catch blocks, error returns)
- Edge cases (null/undefined inputs, empty arrays, boundary values, large inputs)
- Async behavior (promises, callbacks, streams)

---

## Step 3: Plan the Test Suite

Before writing code, outline what you'll test:

### Unit Tests
- Every exported function with representative inputs
- Return values for happy path
- Error handling for invalid inputs
- Boundary values (0, -1, empty string, null, max int, etc.)
- Type coercion edge cases if applicable

### Integration Tests (if the code interacts with other modules)
- Component interactions and data flow
- API calls with mocked responses (success + failure)
- Service layer with mocked dependencies
- State management side effects

### Edge Cases and Error Handling
- Null, undefined, empty inputs
- Malformed data
- Network failures / timeouts
- Concurrent access / race conditions
- Extremely large inputs

---

## Step 4: Write the Tests

Follow these principles:

### Structure

```
describe("[ModuleName]", () => {
  describe("[functionName]", () => {
    it("should [expected behavior] when [condition]", () => {
      // Arrange
      // Act
      // Assert
    });
  });
});
```

- **Descriptive test names** — Read like documentation: "should return empty array when input is null"
- **AAA pattern** — Arrange (setup), Act (execute), Assert (verify). Separate each visually.
- **One assertion per concept** — Multiple `expect()` calls are fine if they assert one logical thing
- **Group with `describe`** — One block per function/method/component behavior
- **Setup/teardown** — Use `beforeEach`/`afterEach` for test isolation. Clean up subscriptions, timers, mocks.

### Mocking Strategy

- Mock **external dependencies only** — Don't mock the code under test
- Use the project's existing mock patterns (e.g., `jest.mock()`, `vi.mock()`, `unittest.mock`)
- Create **test data factories** for complex objects instead of inline literals
- Mock timers (`jest.useFakeTimers()` / `vi.useFakeTimers()`) for time-dependent code
- Mock dates for deterministic snapshots
- Always **restore mocks** in `afterEach` to prevent test pollution

### Async Testing

- Always `await` async functions or return the promise
- Test both resolve and reject paths
- Use `waitFor` / `findBy` for async UI updates (React Testing Library)
- Test loading, success, and error states

### Framework-Specific Guidance

| Framework | Component Testing | Key Patterns |
|-----------|------------------|--------------|
| **React** | React Testing Library | `render()`, `screen.getByRole()`, `userEvent`, `waitFor` |
| **Vue** | Vue Test Utils | `mount()`, `shallowMount()`, `wrapper.find()`, `trigger()` |
| **Angular** | TestBed | `TestBed.configureTestingModule()`, `fixture.detectChanges()` |
| **Node.js** | Supertest | `request(app).get("/api/...").expect(200)` |
| **Python** | pytest | `@pytest.fixture`, `monkeypatch`, parametrize |
| **Go** | testing | `t.Run()`, table-driven tests, `t.Parallel()` |

---

## Step 5: Verify and Improve

After generating the tests:

1. **Run the tests** — Execute the test suite to make sure they pass
2. **Check coverage** — Identify untested lines or branches
3. **Add missing cases** — Fill gaps in coverage, especially error paths
4. **Review test quality** — Tests should fail when the code breaks, not just when the tests break

### Coverage Goals

| Priority | Coverage Target |
|----------|----------------|
| Critical business logic | 90%+ |
| Utility functions | 85%+ |
| UI components | 80%+ |
| Configuration/glue code | 60%+ |

Focus on **branch coverage** over line coverage — untested `else` and `catch` paths are where bugs hide.

---

## Output Checklist

Before finishing, verify:

- [ ] Tests follow the project's existing naming convention and file location
- [ ] All exported functions/components have at least one test
- [ ] Happy path tested for every function
- [ ] Error/failure path tested for every function that can fail
- [ ] Edge cases covered (null, empty, boundary values)
- [ ] External dependencies are mocked (no real API calls, no real DB)
- [ ] Async code is properly awaited
- [ ] Mocks are cleaned up in afterEach
- [ ] Tests are independent — can run in any order
- [ ] Test names read like documentation

© coco-research · MIT · coco-research/coco

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

Все скиллы по теме «Тесты и QA» →
dart-generate-test-mocks dart-lang Скилл dart-generate-test-mocks для юнит-тестов на Dart: агент выносит внешние зависимости в конструктор, генерирует моки через mockito и build_runner, потом пишет тесты. CX Codex +1 20 300установок testing-boss Pedro Nauck Скилл testing-boss задаёт правила создания тестов и эвалов для LLM-агентов: помогает выбрать уровень проверок, починить нестабильные тесты в CI и убрать лишние моки. CX Codex +1 274установок testing-strategy официальный anthropics Скилл testing-strategy для Claude Code проектирует стратегию тестирования и тест-план для компонента. Включается на вопросы о том, как тестировать и какие тесты нужны. CX Codex +1 6 800установок test-coverage-improver OneWave-AI Скилл test-coverage-improver находит пробелы в покрытии тестами и генерирует недостающие тесты для критичных участков кода. CX Codex +1 312установок tdd-workflow travisjneuman Скилл tdd-workflow для Claude Code, Codex, Cursor и других платформ, который включает режим разработки через тесты: сначала пишется падающий тест (RED), потом минимальный код для прохода (GREEN), затем рефакторинг. CX Codex +1 141установок writing-unit-tests riekelt Скилл writing-unit-tests для Claude Code пишет и перерабатывает модульные тесты, проверяющие поведение, а не устройство кода. Перерабатывает нестабильные и трудночитаемые тесты. CX Codex +1 25 700установок

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

Весь набор →
c4-architecture Скилл c4-architecture генерирует архитектурную документацию по модели C4: контекст системы, контейнеры, компоненты и деплоймент в формате Mermaid. CX Codex +1 ★ 328звёзд репо create-subagent Скилл create-subagent помогает создавать изолированных субагентов с готовыми системными промптами для ревью кода, отладки и работы с данными. CX Codex +1 ★ 328звёзд репо create-skill Скилл create-skill помогает проектировать скиллы для ИИ-агентов: объясняет структуру каталогов, разметку SKILL.md и правила формулирования триггеров в описании. CX Codex +1 ★ 328звёзд репо ultra-think Скилл ultra-think для Claude Code разбирает архитектурные развилки с четырёх сторон, сравнивает подходы и выдаёт одну рекомендацию. CX Codex +1 ★ 328звёзд репо m0-handoff Скилл m0-handoff сохраняет состояние сессии в STATE.md и локальный демон M0, чтобы продолжить работу после сжатия контекста или в другой сессии. CX Codex +1 ★ 328звёзд репо goal Хранит активную цель проекта в .goal.md, чтобы агент продолжал работу над задачей между сессиями. CX Codex +1 ★ 328звёзд репо pm-advisor Субагент pm-advisor для управления продуктом: формулирует пользовательские истории, разбивает фичи на задачи и рассчитывает критерии приёмки. CX Codex ★ 328звёзд репо brain:update Скилл brain:update для Claude Code в конце сессии извлекает из разговора решения, задачи, события и связи и записывает их в project_brain.db проекта. CX Codex +1 ★ 328звёзд репо

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

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