Skip to main content
command CX Codex

tdd · sangrokjung — Claude Code command: what it does, how to install

This command guides one task through TDD: define interfaces, write failing tests, implement the minimum, refactor, and check coverage.

MIT ★ 880 updated 2026-09-03

Install into Claude Code · Manually: put the files in place All methods and platforms ↓
.claude/commands/tdd.md
Open on GitHub

What tdd does

The command invokes the tdd-guide agent and breaks a task into a fixed working sequence. It defines input and output interfaces, creates tests before implementation, runs them to confirm the expected failure, then adds only enough code to pass. Once the tests are green, the agent refactors the code and runs the checks again.

Use /tdd for new functions or components, bug fixes, refactoring, and critical business logic. For a bug, the flow starts with a reproduction test, confirms the failure, applies the fix, and confirms the passing result. The final stage checks coverage and adds tests when it falls below 80%. The command allows Agent, Read, Glob, and Grep.

In Claude Code, the command file must be placed at .claude/commands/tdd.md; otherwise /tdd will not be available.

What it helps with

  • define interfaces before writing implementation
  • create a failing test for a new behavior
  • prove a bug fix with a failing-to-passing test
  • check coverage after refactoring

Example prompts for the agent

  • Use /tdd to build a function that calculates a market liquidity score.
  • Use /tdd to reproduce the empty-response bug, then fix it after the test fails.
  • Use /tdd to add a component, cover edge cases, and check for at least 80% test coverage.

How to install tdd

Manually: put the files in place

.claude/commands/tdd.md

Call it with /tdd. For all projects use ~/.claude/commands/

Questions about tdd

How do I install tdd in Claude Code?

Place the command file at .claude/commands/tdd.md.

What does the tdd command do?

It calls the tdd-guide agent to move from interface design and failing tests to a minimal implementation, refactoring, and coverage checks.

How does tdd handle bug fixes?

It starts with a test that reproduces the bug and verifies that the test fails. After the fix, the same test runs again and must pass.

Source text

tdd.md · MIT
---
description: 테스트 먼저 만들고 코드 작성. 한 단위 작업에 사용.
allowed-tools: Agent, Read, Glob, Grep
---

# TDD Command

This command invokes the **tdd-guide** agent to enforce test-driven development methodology.

## What This Command Does

1. **Scaffold Interfaces** - Define types/interfaces first
2. **Generate Tests First** - Write failing tests (RED)
3. **Implement Minimal Code** - Write just enough to pass (GREEN)
4. **Refactor** - Improve code while keeping tests green (REFACTOR)
5. **Verify Coverage** - Ensure 80%+ test coverage

## When to Use

Use `/tdd` when:
- Implementing new features
- Adding new functions/components
- **Fixing bugs** → Prove-It Pattern: 버그 재현 테스트 먼저, 수정은 그 다음
- Refactoring existing code
- Building critical business logic

### Prove-It Pattern (버그 수정 전용)

```
BUG REPORT → REPRODUCE TEST (RED) → VERIFY FAIL → FIX (GREEN) → VERIFY PASS
```

버그 수정 시 "고쳤다"의 증거는 **실패→성공 전환**이다. 테스트 없이 수정하면 증상만 가린 것일 수 있다.

## How It Works

The tdd-guide agent will:

1. **Define interfaces** for inputs/outputs
2. **Write tests that will FAIL** (because code doesn't exist yet)
3. **Run tests** and verify they fail for the right reason
4. **Write minimal implementation** to make tests pass
5. **Run tests** and verify they pass
6. **Refactor** code while keeping tests green
7. **Check coverage** and add more tests if below 80%

## TDD Cycle

```
RED → GREEN → REFACTOR → REPEAT

RED:      Write a failing test
GREEN:    Write minimal code to pass
REFACTOR: Improve code, keep tests passing
REPEAT:   Next feature/scenario
```

## Example Usage

```
User: /tdd I need a function to calculate market liquidity score

Agent (tdd-guide):
# TDD Session: Market Liquidity Score Calculator

## Step 1: Define Interface (SCAFFOLD)

```typescript
// lib/liquidity.ts
export interface MarketData {
  totalVolume: number
  bidAskSpread: number
  activeTraders: number
  lastTradeTime: Date
}

export function calculateLiquidityScore(market: MarketData): number {
  // TODO: Implementation
  throw new Error('Not implemented')
}
```

## Step 2: Write Failing Test (RED)

```typescript
// lib/liquidity.test.ts
import { calculateLiquidityScore } from './liquidity'

describe('calculateLiquidityScore', () => {
  it('should return high score for liquid market', () => {
    const market = {
      totalVolume: 100000,
      bidAskSpread: 0.01,
      activeTraders: 500,
      lastTradeTime: new Date()
    }

    const score = calculateLiquidityScore(market)

    expect(score).toBeGreaterThan(80)
    expect(score).toBeLessThanOrEqual(100)
  })

  it('should return low score for illiquid market', () => {
    const market = {
      totalVolume: 100,
      bidAskSpread: 0.5,
      activeTraders: 2,
      lastTradeTime: new Date(Date.now() - 86400000) // 1 day ago
    }

    const score = calculateLiquidityScore(market)

    expect(score).toBeLessThan(30)
    expect(score).toBeGreaterThanOrEqual(0)
  })

  it('should handle edge case: zero volume', () => {
    const market = {
      totalVolume: 0,
      bidAskSpread: 0,
      activeTraders: 0,
      lastTradeTime: new Date()
    }

    const score = calculateLiquidityScore(market)

    expect(score).toBe(0)
  })
})
```

## Step 3: Run Tests - Verify FAIL

```bash
npm test lib/liquidity.test.ts

FAIL lib/liquidity.test.ts
  ✕ should return high score for liquid market (2 ms)
    Error: Not implemented

1 test failed, 0 passed
```

✅ Tests fail as expected. Ready to implement.

## Step 4: Implement Minimal Code (GREEN)

```typescript
// lib/liquidity.ts
export function calculateLiquidityScore(market: MarketData): number {
  // Handle zero volume edge case
  if (market.totalVolume === 0) {
    return 0
  }

  // Calculate component scores (0-100 scale)
  const volumeScore = Math.min(market.totalVolume / 1000, 100)
  const spreadScore = Math.max(100 - (market.bidAskSpread * 1000), 0)
  const traderScore = Math.min(market.activeTraders / 10, 100)

  // Recent activity bonus
  const hoursSinceLastTrade = (Date.now() - market.lastTradeTime.getTime()) / (1000 * 60 * 60)
  const recencyScore = Math.max(100 - (hoursSinceLastTrade * 10), 0)

  // Weighted average
  const score = (
    volumeScore * 0.4 +
    spreadScore * 0.3 +
    traderScore * 0.2 +
    recencyScore * 0.1
  )

  return Math.min(Math.max(score, 0), 100) // Clamp to 0-100
}
```

## Step 5: Run Tests - Verify PASS

```bash
npm test lib/liquidity.test.ts

PASS lib/liquidity.test.ts
  ✓ should return high score for liquid market (3 ms)
  ✓ should return low score for illiquid market (2 ms)
  ✓ should handle edge case: zero volume (1 ms)

3 tests passed
```

✅ All tests passing!

## Step 6: Refactor (IMPROVE)

```typescript
// lib/liquidity.ts - Refactored with constants and better readability
const WEIGHTS = {
  VOLUME: 0.4,
  SPREAD: 0.3,
  TRADERS: 0.2,
  RECENCY: 0.1,
} as const

const SCALE_FACTORS = {
  VOLUME: 1000,
  SPREAD: 1000,
  TRADERS: 10,
  RECENCY_PENALTY: 10,
} as const

function clamp(value: number, min: number, max: number): number {
  return Math.min(Math.max(value, min), max)
}

export function calculateLiquidityScore(market: MarketData): number {
  if (market.totalVolume === 0) return 0

  const volumeScore = Math.min(market.totalVolume / SCALE_FACTORS.VOLUME, 100)
  const spreadScore = clamp(100 - (market.bidAskSpread * SCALE_FACTORS.SPREAD), 0, 100)
  const traderScore = Math.min(market.activeTraders / SCALE_FACTORS.TRADERS, 100)

  const hoursSinceLastTrade = (Date.now() - market.lastTradeTime.getTime()) / (1000 * 60 * 60)
  const recencyScore = clamp(100 - (hoursSinceLastTrade * SCALE_FACTORS.RECENCY_PENALTY), 0, 100)

  const weightedScore =
    volumeScore * WEIGHTS.VOLUME +
    spreadScore * WEIGHTS.SPREAD +
    traderScore * WEIGHTS.TRADERS +
    recencyScore * WEIGHTS.RECENCY

  return clamp(weightedScore, 0, 100)
}
```

## Step 7: Verify Tests Still Pass

```bash
npm test lib/liquidity.test.ts

PASS lib/liquidity.test.ts
  ✓ should return high score for liquid market (3 ms)
  ✓ should return low score for illiquid market (2 ms)
  ✓ should handle edge case: zero volume (1 ms)

3 tests passed
```

✅ Refactoring complete, tests still passing!

## Step 8: Check Coverage

```bash
npm test -- --coverage lib/liquidity.test.ts

File           | % Stmts | % Branch | % Funcs | % Lines
---------------|---------|----------|---------|--------
liquidity.ts   |   100   |   100    |   100   |   100

Coverage: 100% ✅ (Target: 80%)
```

✅ TDD session complete!
```

## TDD Best Practices

**DO:**
- ✅ Write the test FIRST, before any implementation
- ✅ Run tests and verify they FAIL before implementing
- ✅ Write minimal code to make tests pass
- ✅ Refactor only after tests are green
- ✅ Add edge cases and error scenarios
- ✅ Aim for 80%+ coverage (100% for critical code)

**DON'T:**
- ❌ Write implementation before tests
- ❌ Skip running tests after each change
- ❌ Write too much code at once
- ❌ Ignore failing tests
- ❌ Test implementation details (test behavior)
- ❌ Mock everything (prefer integration tests)

## Test Types to Include

**Unit Tests** (Function-level):
- Happy path scenarios
- Edge cases (empty, null, max values)
- Error conditions
- Boundary values

**Integration Tests** (Component-level):
- API endpoints
- Database operations
- External service calls
- React components with hooks

**E2E Tests** (use `/e2e` command):
- Critical user flows
- Multi-step processes
- Full stack integration

## Coverage Requirements

- **80% minimum** for all code
- **100% required** for:
  - Financial calculations
  - Authentication logic
  - Security-critical code
  - Core business logic

## Important Notes

**MANDATORY**: Tests must be written BEFORE implementation. The TDD cycle is:

1. **RED** - Write failing test
2. **GREEN** - Implement to pass
3. **REFACTOR** - Improve code

Never skip the RED phase. Never write code before tests.

## Integration with Other Commands

- Use `/plan` first to understand what to build
- Use `/tdd` to implement with tests
- Use `/build-and-fix` if build errors occur
- Use `/code-review` to review implementation
- Use `/test-coverage` to verify coverage

## Related Agents

This command invokes the `tdd-guide` agent located at:
`~/.claude/agents/tdd-guide.md`

And can reference the `tdd-workflow` skill at:
`~/.claude/skills/tdd-workflow/`

---

## 다음 단계

구현이 완료되면:
- `/code-review`로 품질 검사

© sangrokjung · MIT · sangrokjung/claude-forge

Similar slash commands

All slash commands for Testing and QA →

tdd by other authors comes first.

tdd Affaan Mustafa tdd enforces a strict test-driven development cycle in Claude Code by writing failing tests first, implementing minimal code, and checking for 80%+ coverage. CX Codex +1 ★ 6,739repo stars w-tdd blockmatic-icebox The w-tdd Claude Code skill guides implementation through red-green-refactor. It activates when a developer requests TDD or the repository requires it. CX Codex +1 647installs tdd-workflow davila7 tdd-workflow guides Claude Code through the test-driven development loop: write a failing test first, make it pass with simple code, then refactor. CX Codex +1 194installs 054-design-tdd Juan Antonio Breña Moral 054-design-tdd — a skill that walks Java developers through red-green-refactor cycles with test-driven development. Write a failing test first, implement just enough code to pass, then refactor while tests stay green. CX Codex +1 177installs tdd-orchestrator davila7 tdd-orchestrator is a Claude Code skill that orchestrates test-driven development through red-green-refactor cycles. It coordinates multi-agent testing workflows and verifies test-first compliance. CX Codex +1 51installs tdd-refactor Seth Hobson This command refactors code through the TDD refactor phase while keeping tests green. Use it for controlled structural changes without altering behavior. CX Codex +1 ★ 42,780repo stars TDD Refactor Phase - Improve Quality & Security official github TDD Refactor Phase - Improve Quality & Security is a GitHub Copilot subagent that refines code after tests pass and checks it against a GitHub issue. It asks for plan approval before editing. CX Codex +1 ★ 41,430repo stars

From the same set44

The whole set →
rca-debugger rca-debugger investigates complex failures when ordinary debugging has stalled, including flaky bugs and differences between CI and local runs. CX Codex ★ 880repo stars security-reviewer security-reviewer scans a diff for OWASP Top 10 flaws, hardcoded secrets and shaky dependencies, then ranks what it finds. You get a report with secure code samples. CX Codex ★ 880repo stars systematic-debugging The systematic-debugging skill guides an agent through finding an error’s cause before suggesting a fix. Use it for failed tests, builds, deployments, configuration conflicts, or repeated failed attempts. CX Codex +1 ★ 880repo stars harness-diet harness-diet — a Claude Code skill that measures the always-loaded context of a harness and pulls it back under budget. Runs when CLAUDE.md and always-on rules have piled up. CX Codex +1 ★ 880repo stars escalation-fixer escalation-fixer — a last-resort subagent for Claude that takes over after narrower build fixes have failed and is allowed to restructure the project to get it green. CX Codex ★ 880repo stars e2e The e2e command for Claude Code generates and runs Playwright end-to-end tests across browsers, capturing screenshots, traces, and reports. CX Codex +1 ★ 880repo stars skill-factory The skill-factory skill reviews work from a session, spots repeatable patterns, and turns selected ones into Claude Code skills. Use it to capture a workflow for reuse. CX Codex +1 ★ 880repo stars skeptical-auditor skeptical-auditor audits another agent's claim that everything passed: reruns the steps and checks the real exit codes. For the case where the agent graded its own work. CX Codex ★ 880repo stars

Project sponsors

Companies that keep this analytics open