tdd-workflow

Test-driven development workflow with comprehensive coverage requirements including unit, integration, and E2E tests

Best use case

tdd-workflow is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Test-driven development workflow with comprehensive coverage requirements including unit, integration, and E2E tests

Teams using tdd-workflow should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/tdd-workflow/SKILL.md --create-dirs "https://raw.githubusercontent.com/organvm-iv-taxis/a-i--skills/main/distributions/claude/skills/tdd-workflow/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/tdd-workflow/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How tdd-workflow Compares

Feature / Agenttdd-workflowStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Test-driven development workflow with comprehensive coverage requirements including unit, integration, and E2E tests

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Test-Driven Development Workflow

Enforces test-driven development principles with comprehensive test coverage across all layers.

## When to Activate

- Writing new features or functionality
- Fixing bugs or issues
- Refactoring existing code
- Adding API endpoints
- Creating new components
- Implementing business logic

## Core Principles

### 1. Tests BEFORE Code
**Always** write tests first, then implement code to make tests pass. No exceptions.

### 2. Coverage Requirements
- Minimum 80% coverage (unit + integration + E2E)
- All edge cases covered
- Error scenarios tested
- Boundary conditions verified
- Happy path and sad path

### 3. Test Pyramid

```
        ┌────────┐
        │   E2E  │  (10-20%)
        ├────────┤
        │  INTEG │  (20-30%)
        ├────────┤
        │  UNIT  │  (50-70%)
        └────────┘
```

## TDD Workflow: Red-Green-Refactor

### Step 1: RED - Write Failing Test

Start with the user story:

```
As a [role], I want to [action], so that [benefit]

Example:
As a user, I want to search for products by category,
so that I can find relevant items quickly.
```

Write the test:

```typescript
describe('ProductSearch', () => {
  it('returns products filtered by category', async () => {
    const products = await searchProducts({ category: 'electronics' });
    
    expect(products).toHaveLength(5);
    expect(products.every(p => p.category === 'electronics')).toBe(true);
  });
});
```

### Step 2: Run Tests (They Should Fail)

```bash
npm test
# ✗ ProductSearch > returns products filtered by category
#   TypeError: searchProducts is not a function
```

**This is good!** Red phase confirms test is working.

### Step 3: GREEN - Implement Minimal Code

Write just enough code to pass:

```typescript
export async function searchProducts(filters: SearchFilters) {
  const { category } = filters;
  return db.products.findMany({
    where: { category }
  });
}
```

### Step 4: Run Tests (They Should Pass)

```bash
npm test
# ✓ ProductSearch > returns products filtered by category (42ms)
```

### Step 5: REFACTOR - Improve Code

Now refactor while keeping tests green:

```typescript
export async function searchProducts(filters: SearchFilters) {
  const query = buildSearchQuery(filters);
  const results = await executeSearch(query);
  return transformResults(results);
}
```

Run tests again to ensure they still pass.

## Test Types

### Unit Tests

**Purpose**: Test individual functions in isolation

```typescript
describe('calculateDiscount', () => {
  it('applies 10% discount for basic tier', () => {
    const price = calculateDiscount(100, 'basic');
    expect(price).toBe(90);
  });

  it('applies 20% discount for premium tier', () => {
    const price = calculateDiscount(100, 'premium');
    expect(price).toBe(80);
  });

  it('throws error for invalid tier', () => {
    expect(() => calculateDiscount(100, 'invalid')).toThrow();
  });
});
```

### Integration Tests

**Purpose**: Test multiple components working together

```typescript
describe('User Registration API', () => {
  it('creates user and sends welcome email', async () => {
    const response = await request(app)
      .post('/api/register')
      .send({ email: 'test@example.com', password: 'secret' });  // allow-secret

    expect(response.status).toBe(201);
    expect(response.body.user.email).toBe('test@example.com');
    
    // Verify email was sent
    const sentEmails = await testEmailService.getSentEmails();
    expect(sentEmails).toHaveLength(1);
    expect(sentEmails[0].to).toBe('test@example.com');
  });
});
```

### E2E Tests (Playwright/Cypress)

**Purpose**: Test complete user flows through the UI

```typescript
test('user can complete checkout process', async ({ page }) => {
  await page.goto('/products');
  await page.click('[data-testid="add-to-cart"]');
  await page.click('[data-testid="cart"]');
  await page.click('[data-testid="checkout"]');
  await page.fill('[name="cardNumber"]', '4242424242424242');
  await page.click('[data-testid="complete-order"]');

  await expect(page.locator('.success-message')).toBeVisible();
  await expect(page).toHaveURL(/\/order-confirmation/);
});
```

## Coverage Verification

After implementation, check coverage:

```bash
npm test -- --coverage

# Output:
# File          | % Stmts | % Branch | % Funcs | % Lines
# --------------|---------|----------|---------|--------
# All files     |   84.2  |   78.5   |   91.3  |   85.1
```

**Requirements:**
- Statements: > 80%
- Branches: > 75%
- Functions: > 85%
- Lines: > 80%

## Edge Cases Checklist

Always test:

- [ ] Empty input
- [ ] Null/undefined values
- [ ] Large datasets
- [ ] Concurrent operations
- [ ] Network failures
- [ ] Database errors
- [ ] Invalid data types
- [ ] Boundary values (0, -1, MAX_INT)
- [ ] Unauthorized access
- [ ] Rate limiting

## Mocking Strategy

### When to Mock

- External APIs
- Database calls (in unit tests)
- Time-dependent functions
- File system operations
- Third-party services

### Example Mocks

```typescript
// Mock external service
vi.mock('./emailService', () => ({
  sendEmail: vi.fn().mockResolvedValue({ success: true })
}));

// Mock database
vi.mock('./db', () => ({
  users: {
    findUnique: vi.fn().mockResolvedValue({ id: 1, name: 'Test' })
  }
}));

// Mock Date.now()
vi.spyOn(Date, 'now').mockReturnValue(1234567890000);
```

## Test Organization

```
src/
  features/
    products/
      product.service.ts
      product.service.test.ts      # Unit tests
      product.integration.test.ts  # Integration tests
      product.e2e.test.ts          # E2E tests
```

## Debugging Failed Tests

```bash
# Run single test file
npm test -- product.service.test.ts

# Run single test
npm test -- -t "calculates discount correctly"

# Run in watch mode
npm test -- --watch

# Run with coverage
npm test -- --coverage --no-cache
```

## Integration Points

Complements:
- **verification-loop**: For pre-commit verification
- **testing-patterns**: For test design patterns
- **deployment-cicd**: For CI test execution
- **security-implementation-guide**: For security testing

## Workflow Summary

1. **RED**: Write failing test
2. **GREEN**: Implement minimal code
3. **REFACTOR**: Improve while keeping tests green
4. **VERIFY**: Check coverage meets requirements
5. **COMMIT**: Only commit if all tests pass

Never skip steps. Never commit untested code.

---

## Related Skills

### Complementary Skills (Use Together)
- **[testing-patterns](../testing-patterns/)** - Comprehensive test patterns for unit, integration, and E2E tests
- **[verification-loop](../verification-loop/)** - Pre-commit verification workflow that validates all quality gates
- **[deployment-cicd](../deployment-cicd/)** - CI pipeline setup for automated test execution

### Alternative Skills (Similar Purpose)
- None - TDD is a specific methodology that complements other testing approaches

### Prerequisite Skills (Learn First)
- **[testing-patterns](../testing-patterns/)** - Understanding test types and frameworks helps with TDD

Related Skills

research-synthesis-workflow

5
from organvm-iv-taxis/a-i--skills

Systematic methodology for gathering, analyzing, and synthesizing research from multiple sources into coherent insights and actionable knowledge.

feature-workflow-orchestrator

5
from organvm-iv-taxis/a-i--skills

End-to-end feature development orchestration from planning through deployment with quality gates

taxonomy-modeling-design

5
from organvm-iv-taxis/a-i--skills

Phase 2 of the pentaphase structural-overhaul protocol. Classifies entities, standardizes attributes, establishes relationships, and designs the access framework. Use when the user invokes phase 2 of an overhaul, asks to "design the taxonomy" or "model the structure", or has completed a landscape audit and is ready to redesign. Consumes phase-1-landscape-report.md; produces phase-2-taxonomy-model.md.

systemic-ingestion-normalization

5
from organvm-iv-taxis/a-i--skills

Phase 4 of the pentaphase structural-overhaul protocol. Purges redundancies, enriches and aligns legacy entities to the new schema, executes phased ingestion into the new environment, and audits integrity. Use when the user invokes phase 4 of an overhaul, asks to "migrate the data" or "ingest into the new system", or has a configured environment ready to accept legacy entities. Consumes phase-3-environment-spec.md; produces phase-4-ingestion-report.md.

system-environment-configuration

5
from organvm-iv-taxis/a-i--skills

Phase 3 of the pentaphase structural-overhaul protocol. Translates the taxonomy model into objective technical criteria, evaluates candidate mechanisms or frameworks, instantiates the chosen architecture, and programs validation rules. Use when the user invokes phase 3 of an overhaul, asks to "select a system" or "configure the environment", or has a taxonomy model and is ready to choose technology. Consumes phase-2-taxonomy-model.md; produces phase-3-environment-spec.md.

pentaphase-orchestrator

5
from organvm-iv-taxis/a-i--skills

Threads the full five-phase structural-overhaul protocol — landscape discovery, taxonomy design, environment configuration, systemic ingestion, governance evolution — for any substrate the user names. Use when the user requests a structural overhaul, system redesign, or end-to-end restructuring of a documentation system, asset registry, code monorepo, knowledge base, or operational workflow; or when they explicitly invoke the pentaphase methodology. Coordinates handoffs between phase-skills and seats validation gates between phases.

landscape-discovery-audit

5
from organvm-iv-taxis/a-i--skills

Phase 1 of the pentaphase structural-overhaul protocol. Inventories assets, maps current flow, identifies friction, and defines value metrics for any substrate. Use when the user invokes phase 1 of an overhaul, requests a baseline audit, asks to "discover the landscape" of a system, or wants to understand current state before redesigning. Produces phase-1-landscape-report.md.

governance-evolution-protocol

5
from organvm-iv-taxis/a-i--skills

Phase 5 of the pentaphase structural-overhaul protocol. Codifies operational protocols, onboards the ecosystem of participants, programs behavior monitoring, and establishes an iteration cadence so the substrate evolves rather than calcifies. Use when the user invokes phase 5 of an overhaul, asks to "establish governance" or "lock in the protocols", or has completed ingestion and is ready to declare the substrate operational. Consumes phase-4-ingestion-report.md; produces phase-5-governance-charter.md, which closes the protocol.

dimension-surfacing

5
from organvm-iv-taxis/a-i--skills

Surfaces the parallel domain dimensions implicit in a dense or minimal prompt. Use when a user prompt is small on the surface but plainly implies multiple independent domains needing different expertise; when explicitly invoked by the coliseum-orchestrator skill as Phase 1; or when the user asks "what dimensions does this prompt encode" or "what axes does this break into." Produces a named dimension set where each dimension is independently executable and not a paraphrase of another.

coliseum-dispatch

5
from organvm-iv-taxis/a-i--skills

Dispatches a composed set of assignment envelopes to domain-expert subagents in parallel, in a single message with multiple Agent tool calls. Enforces the no-pingpong gate via the pingpong-detector agent before any dispatch fires. Use when invoked by the coliseum-orchestrator as Phase 3; when envelopes are already composed and the next step is parallel execution; or when the user asks to "fan out" or "dispatch in parallel." Produces a dispatch log capturing what was sent, when, and where returns land.

assignment-composition

5
from organvm-iv-taxis/a-i--skills

Wraps each surfaced dimension as a self-contained 9-section autonomous-work-assignment envelope — scope, context, success criteria, allowed tools, return format, handoff — all the recipient subagent needs to execute without coming back. Use when invoked by coliseum-orchestrator as Phase 2; when dimensions are named and the next step is to make each independently dispatchable; or when the user asks "compose this as an assignment." The no-pingpong gate validates each envelope before dispatch.

workspace-autopsy-governance

5
from organvm-iv-taxis/a-i--skills

Conducts a full automated autopsy of the current workspace directory to map files, identifies structural issues, proposes a restructuring plan (the signal), and establishes unified governance using templates. Use this skill when a user asks to map, restructure, reorganize, or apply new governance to an existing messy repository.