Claude
Skills
Sign in
Back

tdd-guide

Included with Lifetime
$97 forever

Guides red-green-refactor TDD workflows with test generation, coverage gap analysis, and multi-framework support. Use when writing tests first, analyzing coverage reports, generating test stubs, or converting tests between Jest, Pytest, JUnit, and Vitest.

Writing & Docsscriptsassets

What this skill does

# TDD Guide

The agent guides red-green-refactor TDD workflows, generates framework-specific test stubs from requirements, parses coverage reports to identify prioritized gaps, and calculates test quality metrics including smell detection and assertion density. Supports Jest, Pytest, JUnit, Vitest, and Mocha.

## Quick Start

```bash
# Generate test cases from requirements (Python API)
from test_generator import TestGenerator, TestFramework
gen = TestGenerator(framework=TestFramework.PYTEST, language="python")
cases = gen.generate_from_requirements(requirements)

# Analyze coverage gaps from LCOV report
from coverage_analyzer import CoverageAnalyzer
analyzer = CoverageAnalyzer()
analyzer.parse_coverage_report(content, "lcov")
gaps = analyzer.identify_gaps(threshold=80.0)

# Guide TDD cycle
from tdd_workflow import TDDWorkflow
wf = TDDWorkflow()
wf.start_cycle("User can reset password via email")
```

---

## Core Workflows

### Workflow 1: TDD a New Feature

1. Write a failing test for the feature requirement (RED phase)
2. Call `validate_red_phase()` -- confirms test exists and fails
3. Write minimal code to make the test pass (GREEN phase)
4. Call `validate_green_phase()` -- confirms all tests pass
5. Refactor while keeping tests green (REFACTOR phase)
6. Call `validate_refactor_phase()` -- confirms tests still pass after cleanup
7. **Validation checkpoint:** Each cycle completes in under 10 minutes; zero test smells introduced

### Workflow 2: Analyze Coverage Gaps

1. Generate coverage report: `npm test -- --coverage` or `pytest --cov`
2. Detect format with `detect_format()` and parse with `parse_coverage_report()`
3. Run `identify_gaps(threshold=80.0)` to get prioritized file list (P0/P1/P2)
4. Generate test stubs for P0 files (business-critical, lowest coverage)
5. **Validation checkpoint:** Line coverage >= 80%; branch coverage >= 70%; zero P0 gaps in critical paths

### Workflow 3: Generate Tests from Requirements

1. Structure requirements as user stories with acceptance criteria
2. Call `generate_from_requirements()` with target framework
3. Review generated test cases for completeness (happy path, error, edge cases)
4. Generate test file with `generate_test_file()`
5. **Validation checkpoint:** Each acceptance criterion has at least one test; all tests compile

---

## Tools

| Tool | Purpose |
|------|---------|
| `test_generator.py` | Generate test cases from requirements/specs |
| `coverage_analyzer.py` | Parse LCOV/JSON/XML reports, find gaps |
| `tdd_workflow.py` | Guide red-green-refactor cycles |
| `framework_adapter.py` | Convert tests between frameworks |
| `fixture_generator.py` | Generate test data and mocks with seeds |
| `metrics_calculator.py` | Calculate complexity and test quality |
| `format_detector.py` | Auto-detect language and framework |
| `output_formatter.py` | Format output for CLI/desktop/CI |

---

## Anti-Patterns

- **Tests that pass immediately** -- a test with no real assertion or `assert True` skips the RED phase; every test must fail before implementation
- **Testing implementation details** -- coupling tests to internal method names makes refactoring break tests; test behavior and outputs, not internals
- **Non-deterministic fixtures** -- random data without a seed produces different failures across CI runs; always pass `seed=<int>` to `FixtureGenerator`
- **Skipping the refactor phase** -- GREEN code that works but is messy accumulates; refactoring is not optional in TDD
- **Coverage theater** -- writing tests that hit lines without meaningful assertions; use `metrics_calculator.py` to detect low assertion density
- **Conditional test logic** -- `if/else` inside tests masks failures; each test should have a single clear path

---

## Troubleshooting

| Problem | Cause | Solution |
|---------|-------|----------|
| Generated tests pass immediately (no RED phase) | Test has no real assertion or asserts a trivially true value | Ensure every test contains an assertion against the actual unit under test; remove placeholder `assert True` stubs before running |
| Coverage report fails to parse | Report format does not match the expected LCOV, JSON, or XML structure | Run `format_detector.py` first to verify the detected format; convert non-standard reports (e.g., Clover) to Cobertura XML |
| Framework adapter produces wrong import style | Source and target framework were swapped, or language/framework mismatch | Verify the `framework` and `language` arguments match your project; use `detect_framework()` on existing test code to auto-detect |
| Fixture generator produces non-deterministic data | No random seed was supplied, so each run yields different values | Pass `seed=<int>` to `FixtureGenerator()` for reproducible fixtures across CI runs |
| Metrics calculator reports 0 test functions | Test code uses an unsupported naming convention (e.g., `spec_` prefix) | Rename tests to follow `test_*` / `it()` / `@Test` conventions, or extend the regex patterns in `_count_test_functions()` |
| TDD workflow validates GREEN phase but tests still fail locally | Test result dict passed to `validate_green_phase()` has `status` not set to `"passed"` | Ensure your test runner output is normalized to `{"status": "passed"}` or `{"status": "failed"}` before passing it in |
| Coverage gaps list is empty despite low overall coverage | All individual files meet the threshold even though the aggregate does not | Lower the `threshold` argument in `identify_gaps()` or inspect per-file coverage with `get_file_coverage()` |

---

## Success Criteria

- **Test-first ratio above 80%** -- at least 4 out of every 5 features begin with a failing test before any implementation code is written.
- **Red-green-refactor cycle under 10 minutes** -- each TDD micro-cycle (write failing test, make it pass, refactor) completes within a single focused interval.
- **Line coverage at or above 80%** -- measured by `coverage_analyzer.py` against LCOV/JSON/XML reports, with branch coverage at or above 70%.
- **Test quality score at or above 75/100** -- as reported by `metrics_calculator.py`, combining assertion density, isolation, naming quality, and absence of test smells.
- **Zero P0 coverage gaps in critical paths** -- business-critical modules (auth, payments, data persistence) have no files flagged P0 by `identify_gaps()`.
- **Test smell count of zero for high-severity items** -- no `missing_assertions`, `sleepy_test`, or `conditional_test_logic` smells detected at high severity.
- **Fixture reproducibility across CI** -- all generated fixtures use a fixed seed and produce identical output on every pipeline run.

---

## Scope & Limitations

**This skill covers:**
- Unit test generation, scaffolding, and stub creation for Jest, Pytest, JUnit, Vitest, and Mocha
- Static coverage report parsing (LCOV, JSON/Istanbul, XML/Cobertura) with gap identification and prioritized recommendations
- Red-green-refactor workflow guidance with phase validation and cycle tracking
- Test quality assessment including complexity analysis, isolation scoring, naming quality, and test smell detection

**This skill does NOT cover:**
- Integration, end-to-end, or performance test generation -- see `senior-qa` for E2E patterns and `senior-devops` for load testing
- Runtime test execution or live coverage measurement -- scripts perform static analysis only; you must run your test suite externally
- Visual/snapshot testing or browser-based test workflows -- use Playwright, Cypress, or Storybook for UI-level testing
- Security-focused test generation (fuzz testing, penetration testing) -- see `senior-security` and `senior-secops` skills

---

## Integration Points

| Skill | Integration | Data Flow |
|-------|-------------|-----------|
| `senior-qa` | Generated test stubs feed into QA review workflows; QA coverage standards inform threshold settings | `test_generator.py` output → QA review → approved test suite |
| `code-reviewer` | Metrics calculator output provides quantitative d
Files: 18
Size: 183.6 KB
Complexity: 91/100
Category: Writing & Docs

Related in Writing & Docs