Backend TDD Mode
Purpose
Transform backend development from waterfall (code → tests) to iterative TDD (test → code → refactor), where tests drive design decisions and Clean Architecture emerges from test requirements.
Prerequisites: This skill assumes familiarity with nestjs-architect for DDD, Clean Architecture, and NestJS integration patterns.
Activation Triggers
- Flags:
--modo-backend-tdd, --tdd-clean-architecture, --strict-quality-mode
- Verbal: "Start with unit tests", "Follow TDD rigorously", "Tests first"
- Context: PRD/TechSpec requires coverage ≥80%, refactoring critical services, MVP with mandatory quality gates
Behavioral Changes
- Tests First - Draft test specifications BEFORE any production code; never implement without failing test
- Dependency Inversion - Define interfaces/contracts before implementations; inject via DI
- Continuous Refinement - After each Red-Green cycle, eliminate coupling/duplication
- Visible Metrics - Communicate coverage, complexity, execution time as part of decisions
Core Process: Red-Green-Refactor (7 Steps)
Execute iteratively for each use case:
Step 1: Confirm Context
- Validate task objective, acceptance criteria, quality indicators (coverage ≥80%, complexity <10, execution <5s)
Step 2: Model Contracts
Step 3: Write Tests (RED)
- Create
.spec.ts files in __tests__ directories per testing patterns
- Cover happy path + critical edge cases
- Use Arrange-Act-Assert pattern
Step 4: Execute and Validate Failure (RED)
- Run
npm run test and confirm ALL new tests FAIL
- If tests pass without implementation, review test validity
Step 5: Implement Minimum Code (GREEN)
- Write minimal code to make tests pass
- Follow architecture principles for layer separation (domain/application/infrastructure)
- Apply TypeScript strictness (no
any, strict mode enabled)
- Run
npm run test and confirm GREEN
Step 6: Refactor (REFACTOR)
- Eliminate duplication and coupling while keeping tests green
- Verify Clean Architecture compliance (dependencies point inward)
- Run
npm run test continuously during refactoring
Step 7: Register Metrics
- Execute
npm run test:cov for coverage report
- Document: coverage %, complexity, execution time
- Evaluate if more scenarios need coverage. If yes, return to Step 2 for next use case.
Expected Outcomes
Validate TDD application by verifying:
- Test files created BEFORE production code (verify timestamps/commits)
- Initial RED state documented (console logs showing failures)
- Implementation organized per architecture structure (core/domain, core/application, core/infra)
- Interfaces and contracts explicit (repositories.interface.ts, use-cases.interface.ts)
- Metrics documented: coverage ≥80%, complexity <10, execution <5s
Quality Standards
Mandatory criteria:
- Tests First - NO production code without failing test; commits show tests → implementation
- Segregated Layers - Follow architecture structure (domain isolated, unidirectional dependencies)
- Testable Interfaces - All external dependencies via interfaces with fakes/stubs per repositories
- Objective Metrics - Run
npm run test:cov, verify thresholds, document results
- Documentation - Architectural decisions and metrics in
tasks.md or dev-log/
Example: Transformation
Standard (Waterfall):
// 1. Implement service directly with Prisma
@Injectable()
export class PedidosService {
constructor(private prisma: PrismaClient) {} // Tight coupling
async listarPedidos() {
return this.prisma.pedido.findMany();
}
}
// 2. Write tests afterward
TDD Mode:
// 1. Define interface (contract)
export interface IPedidosRepository {
findAll(): Promise<Pedido[]>;
}
// 2. Write failing test with stub
it('should return all orders', async () => {
repositoryStub.findAll.resolves(mockPedidos);
const result = await useCase.execute();
expect(result).toEqual(mockPedidos);
});
// 3. Implement use case (GREEN)
export class ListarPedidosUseCase {
constructor(private readonly repo: IPedidosRepository) {}
async execute(): Promise<Pedido[]> {
return this.repo.findAll();
}
}
// 4. Implement repository (concrete)
export class PedidosPrismaRepository implements IPedidosRepository {
constructor(private prisma: PrismaService) {}
async findAll(): Promise<Pedido[]> { /* ... */ }
}
Result: Decoupled design, testable with stubs, swappable implementations.
Integration Points
- With nestjs-architect: Apply TDD methodology to DDD/Clean Architecture patterns
- With backend-nestjs agent: Agent executes this skill when TDD mode activated
- With executar-tarefa workflow: Modifies Sections 2 (modeling), 4 (implementation), 5 (validation)
- With architecture guidelines: References testing, observability
References
- Architectural patterns: See nestjs-architect
- Testing patterns: See testing section
- Books: "Test Driven Development: By Example" (Kent Beck), "Clean Architecture" (Robert C. Martin)
1---2name: mode-backend-tdd3description: Methodological skill for Test-Driven Development in NestJS backend. This skill should be used when strict quality requirements demand tests-first approach, refactoring critical services, or building MVPs with mandatory coverage. Complements nestjs-architect skill with TDD methodology.4---5
6# Backend TDD Mode
7
8## Purpose
9
10Transform backend development from waterfall (code → tests) to iterative TDD (test → code → refactor), where tests drive design decisions and Clean Architecture emerges from test requirements.
11
12**Prerequisites:** This skill assumes familiarity with [nestjs-architect](../nestjs-architect/SKILL-LITE.md) for DDD, Clean Architecture, and NestJS integration patterns.
13
14## Activation Triggers
15
16- Flags: `--modo-backend-tdd`, `--tdd-clean-architecture`, `--strict-quality-mode`
17- Verbal: "Start with unit tests", "Follow TDD rigorously", "Tests first"
18- Context: PRD/TechSpec requires coverage ≥80%, refactoring critical services, MVP with mandatory quality gates
19
20## Behavioral Changes
21
221. **Tests First** - Draft test specifications BEFORE any production code; never implement without failing test
232. **Dependency Inversion** - Define interfaces/contracts before implementations; inject via DI
243. **Continuous Refinement** - After each Red-Green cycle, eliminate coupling/duplication
254. **Visible Metrics** - Communicate coverage, complexity, execution time as part of decisions
26
27## Core Process: Red-Green-Refactor (7 Steps)
28
29Execute iteratively for each use case:
30
31**Step 1: Confirm Context**
32
33- Validate task objective, acceptance criteria, quality indicators (coverage ≥80%, complexity <10, execution <5s)
34
35**Step 2: Model Contracts**
36
37- Define interfaces (repositories, services) before implementations
38- Follow [aggregates](../nestjs-architect/sections/aggregates.md) and [repositories](../nestjs-architect/sections/repositories.md) patterns
39
40**Step 3: Write Tests (RED)**
41
42- Create `.spec.ts` files in `__tests__` directories per [testing patterns](../nestjs-architect/sections/testing.md)
43- Cover happy path + critical edge cases
44- Use Arrange-Act-Assert pattern
45
46**Step 4: Execute and Validate Failure (RED)**
47
48- Run `npm run test` and confirm ALL new tests FAIL
49- If tests pass without implementation, review test validity
50
51**Step 5: Implement Minimum Code (GREEN)**
52
53- Write minimal code to make tests pass
54- Follow [architecture principles](../nestjs-architect/sections/architecture.md) for layer separation (domain/application/infrastructure)
55- Apply TypeScript strictness (no `any`, strict mode enabled)
56- Run `npm run test` and confirm GREEN
57
58**Step 6: Refactor (REFACTOR)**
59
60- Eliminate duplication and coupling while keeping tests green
61- Verify Clean Architecture compliance (dependencies point inward)
62- Run `npm run test` continuously during refactoring
63
64**Step 7: Register Metrics**
65
66- Execute `npm run test:cov` for coverage report
67- Document: coverage %, complexity, execution time
68- **Evaluate if more scenarios need coverage. If yes, return to Step 2 for next use case.**
69
70## Expected Outcomes
71
72Validate TDD application by verifying:
73
741. Test files created BEFORE production code (verify timestamps/commits)
752. Initial RED state documented (console logs showing failures)
763. Implementation organized per [architecture structure](../nestjs-architect/SKILL-LITE.md#2-estrutura-mínima) (core/domain, core/application, core/infra)
774. Interfaces and contracts explicit (repositories.interface.ts, use-cases.interface.ts)
785. Metrics documented: coverage ≥80%, complexity <10, execution <5s
79
80## Quality Standards
81
82**Mandatory criteria:**
83
841. **Tests First** - NO production code without failing test; commits show tests → implementation
852. **Segregated Layers** - Follow [architecture structure](../nestjs-architect/sections/architecture.md) (domain isolated, unidirectional dependencies)
863. **Testable Interfaces** - All external dependencies via interfaces with fakes/stubs per [repositories](../nestjs-architect/sections/repositories.md)
874. **Objective Metrics** - Run `npm run test:cov`, verify thresholds, document results
885. **Documentation** - Architectural decisions and metrics in `tasks.md` or `dev-log/`
89
90## Example: Transformation
91
92**Standard (Waterfall):**
93
94```typescript
95// 1. Implement service directly with Prisma
96@Injectable()
97export class PedidosService {
98 constructor(private prisma: PrismaClient) {} // Tight coupling
99 async listarPedidos() {
100 return this.prisma.pedido.findMany();
101 }
102}
103// 2. Write tests afterward
104```
105
106**TDD Mode:**
107
108```typescript
109// 1. Define interface (contract)
110export interface IPedidosRepository {
111 findAll(): Promise<Pedido[]>;
112}
113
114// 2. Write failing test with stub
115it('should return all orders', async () => {
116 repositoryStub.findAll.resolves(mockPedidos);
117 const result = await useCase.execute();
118 expect(result).toEqual(mockPedidos);
119});
120
121// 3. Implement use case (GREEN)
122export class ListarPedidosUseCase {
123 constructor(private readonly repo: IPedidosRepository) {}
124 async execute(): Promise<Pedido[]> {
125 return this.repo.findAll();
126 }
127}
128
129// 4. Implement repository (concrete)
130export class PedidosPrismaRepository implements IPedidosRepository {
131 constructor(private prisma: PrismaService) {}
132 async findAll(): Promise<Pedido[]> { /* ... */ }
133}
134```
135
136**Result:** Decoupled design, testable with stubs, swappable implementations.
137
138## Integration Points
139
140- **With nestjs-architect:** Apply TDD methodology to [DDD/Clean Architecture patterns](../nestjs-architect/SKILL-LITE.md)
141- **With backend-nestjs agent:** Agent executes this skill when TDD mode activated
142- **With executar-tarefa workflow:** Modifies Sections 2 (modeling), 4 (implementation), 5 (validation)
143- **With architecture guidelines:** References [testing](../nestjs-architect/sections/testing.md), [observability](../nestjs-architect/sections/infra-observability.md)
144
145## References
146
147- **Architectural patterns:** See [nestjs-architect](../nestjs-architect/SKILL-LITE.md)
148- **Testing patterns:** See [testing section](../nestjs-architect/sections/testing.md)
149- **Books:** "Test Driven Development: By Example" (Kent Beck), "Clean Architecture" (Robert C. Martin)