Desarrollo dirigido por pruebas con Claude Code
Aprenda sobre TDD usando Claude Code. Incluye ejemplos practicos de codigo y guia paso a paso.
The Power of TDD x Claude Code
Test-driven development (TDD) follows the cycle of “write a test, confirm it fails, implement, make the test pass, refactor.” Claude Code can autonomously run this entire cycle, dramatically lowering the barrier to practicing TDD.
Red-Green-Refactor in One Shot
Here’s how to delegate the entire TDD cycle to Claude Code at once.
> Implement a user registration feature with the following spec using TDD:
> - Email address validation
> - Password must be 8+ characters with upper/lowercase letters and numbers
> - Prevent duplicate email registration
>
> 1. Write the tests first
> 2. Confirm the tests fail
> 3. Implement and make the tests pass
> 4. Refactor
Example Tests Generated by Claude Code
import { describe, it, expect } from "vitest";
import { registerUser, ValidationError } from "./auth";
describe("registerUser", () => {
it("registers successfully with valid email and password", async () => {
const result = await registerUser({
email: "[email protected]",
password: "Passw0rd",
});
expect(result.success).toBe(true);
expect(result.user.email).toBe("[email protected]");
});
it("throws error for invalid email address", async () => {
await expect(
registerUser({ email: "invalid", password: "Passw0rd" })
).rejects.toThrow(ValidationError);
});
it("throws error for short password", async () => {
await expect(
registerUser({ email: "[email protected]", password: "Pass1" })
).rejects.toThrow("at least 8 characters");
});
it("throws error for password without numbers", async () => {
await expect(
registerUser({ email: "[email protected]", password: "Password" })
).rejects.toThrow("must contain a number");
});
it("throws error for duplicate email address", async () => {
await registerUser({
email: "[email protected]",
password: "Passw0rd",
});
await expect(
registerUser({ email: "[email protected]", password: "Passw0rd" })
).rejects.toThrow("already registered");
});
});
Test-First Prompt Patterns
Pattern 1: Generate Tests from Specifications
> Write tests based on the following API specification.
> Don't implement anything yet.
This two-stage approach lets you write tests first, review them, and then proceed to implementation.
Pattern 2: Add Tests to Existing Code Before Refactoring
> src/utils/formatter.ts has no tests.
> First write tests that guarantee the current behavior,
> then refactor the code.
This pattern is effective for improving legacy code. For details, see the Legacy Code Modernization Guide.
Pattern 3: Auto-Generate Boundary Value Tests
> Create comprehensive boundary value tests for the calculatePrice function.
> Cover 0, negative numbers, maximum values, and decimal rounding.
describe("calculatePrice", () => {
it("returns 0 for quantity of 0", () => {
expect(calculatePrice(100, 0)).toBe(0);
});
it("throws error for negative quantity", () => {
expect(() => calculatePrice(100, -1)).toThrow();
});
it("rounds decimal places correctly", () => {
expect(calculatePrice(33, 3)).toBe(99);
});
it("applies discount for bulk orders", () => {
expect(calculatePrice(100, 1000)).toBe(90000); // 10% discount
});
});
Automate the TDD Cycle with Hooks
Using Claude Code’s hooks feature, you can automatically run tests every time a file changes.
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"command": "npx vitest related \"$CLAUDE_FILE_PATH\" --run 2>&1 | tail -20"
}
]
}
}
For details on hooks, see the Hooks Feature Guide.
Enforce TDD Rules with CLAUDE.md
By writing rules in your project’s CLAUDE.md, Claude Code will always follow a TDD style.
## Development Style
- All new features must be implemented using TDD
- Write tests first and confirm they fail before implementing
- Maintain test coverage above 80%
- Place test files in the __tests__ directory
Combining with Test Strategy
Beyond writing unit tests with TDD, it’s important to build a comprehensive test strategy that includes integration tests and E2E tests. For overall test design, see the Complete Testing Strategy Guide.
Summary
The combination of Claude Code and TDD is a powerful approach that eliminates the tedium of writing tests while maintaining code quality. Start by trying the TDD style with small functions.
For more on writing tests and configuration, refer to the official Anthropic documentation and the Vitest official site.
PDF gratuito: Hoja de trucos de Claude Code en 5 minutos
Solo deja tu correo y te enviaremos al instante la hoja de trucos en una página A4.
Cuidamos tus datos personales y nunca enviamos spam.
Sobre el autor
Masa
Ingeniero apasionado por Claude Code. Dirige claudecode-lab.com, un medio tecnológico en 10 idiomas con más de 2.000 páginas.
Artículos relacionados
7 comprobaciones antes de publicar cada día un artículo multilingüe sobre Claude Code
Una lista práctica para publicar artículos multilingües sobre Claude Code todos los días sin olvidar idiomas, romper CTAs ni dejar páginas antiguas en producción.
Que es Codex Automations y como dejar que la IA gestione contenido mientras duermes
Guia practica para usar Codex Automations en analitica, articulos, CTA, despliegue y monetizacion.
Claude Code × GCP Cloud Functions Guía Completa | Desarrollo Serverless Ultrarrápido
Optimiza GCP Cloud Functions con Claude Code. Implementa triggers HTTP/Pub/Sub/Firestore, pruebas locales y automatización de despliegues con ejemplos de código reales de la experiencia de Masa.