# Building Stories With Tdd

> Orchestrates Test-Driven Development (TDD) workflows for user stories and features. Creates story tests first in tests/stories/, then iteratively implements until all pass. Invoke directly when a developer requests "TDD", "test-driven", "test first", "story test", "write tests before code", or feature implementation with TDD. Coordinates with generating-nest-servers (backend) and developing-lt-frontend (frontend). NOT for direct NestJS coding without TDD (use generating-nest-servers). NOT for standalone test generation (use /test-generate). Use when this capability is needed.

- Skill: `tomevault-io/building-stories-with-tdd` (Agent Skill, multi-file: 2 files)
- Install (CLI): `npx skillmds@latest add tomevault-io/building-stories-with-tdd`
- Raw SKILL.md: https://api.skillmd.com/api/skills/tomevault-io/building-stories-with-tdd/raw
- Safety review: pending (external: skill-scanner PASS, skillspector CAUTION)
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Web & Frontend
- Author: tomevault-io (https://skillmd.com/u/tomevault-io)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/tomevault-io/building-stories-with-tdd

---


# Story-Based Test-Driven Development Expert

You are an expert in Test-Driven Development (TDD) for NestJS applications using @lenne.tech/nest-server. You help developers implement new features by first creating comprehensive story tests, then iteratively developing the code until all tests pass.

## Ecosystem Context

TDD works in the **Lerna fullstack monorepo** created via `lt fullstack init`:
- **Backend tests** (`projects/api/tests/stories/`): API tests for `nest-server-starter` / `@lenne.tech/nest-server`
- **Frontend E2E tests** (`projects/app/tests/`): Playwright tests for `nuxt-base-starter` / `@lenne.tech/nuxt-extensions`

## When to Use This Skill

**ALWAYS use this skill for:**
- Implementing new API features using Test-Driven Development
- Creating story tests for user stories or requirements
- Developing new functionality in a test-first approach
- Ensuring comprehensive test coverage for new features
- Iterative development with test validation
- **Fullstack TDD workflows** (Backend + Frontend E2E tests)

## Fullstack TDD Workflow

**For fullstack projects, follow this order:**

```
Phase 1: BACKEND
├── 1. Write Backend Tests (API tests for REST/GraphQL)
└── 2. Implement Backend against tests (iterate until green)

Phase 2: FRONTEND
├── 3. Write Frontend E2E Tests (Playwright)
└── 4. Implement Frontend against tests (iterate until green)

Phase 3: VERIFICATION
└── 5. Debug with Chrome DevTools MCP (default for direct testing/debugging)
```

**Complete workflow details: [fullstack-tdd-workflow.md](${CLAUDE_SKILL_DIR}/fullstack-tdd-workflow.md)**

### Parallel Test Writing (Agent Teams)

When ALL of these conditions are met, use **parallel test writing** via `coordinating-agent-teams` Pattern 2 (Parallel With Handoff):

1. Agent Teams feature flag is enabled (`CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`)
2. Fullstack monorepo detected (`projects/api/` AND `projects/app/`)
3. Story scope involves both backend AND frontend changes

**Parallel workflow:**
```
Phase 0: CONTRACT DEFINITION (Lead)
└── Define API contracts from story requirements (endpoints, request/response shapes)

Phase 1: PARALLEL TEST WRITING (2 teammates, simultaneous)
├── Teammate "backend-tests": Write API tests using contracts → share via message
└── Teammate "frontend-tests": Write E2E tests using contracts → consume API shapes

Phase 2: CONTRACT VALIDATION (Lead)
└── Verify backend and frontend tests reference consistent contracts

Phase 3: SEQUENTIAL IMPLEMENTATION (standard TDD)
├── Backend implementation (iterate until API tests green)
└── Frontend implementation (iterate until E2E tests green)
```

**Key:** Only test *writing* is parallelized. Implementation remains sequential (backend before frontend) because frontend depends on generated types from the running backend API.

### Test Isolation & Cleanup (CRITICAL)

**Tests MUST be repeatable without side effects:**

1. **Unique test data** - Use `${Date.now()}-${random}` patterns
2. **Complete cleanup in `afterAll`** - Delete all created entities
3. **Separate test database** - `app-test` vs `app-dev`
4. **No cross-test dependencies** - Each test file is independent

```typescript
afterAll(async () => {
  // Delete test-created entities
  await db.collection('entities').deleteMany({ createdBy: testUserId });
  // Delete test users
  await db.collection('users').deleteMany({ email: /@test\.com$/ });
});
```

**Why this matters:** Enables unlimited test runs without manual database cleanup.

## Skill Boundaries

| User Intent | Correct Skill |
|------------|---------------|
| "Implement with TDD" | **THIS SKILL** |
| "Write tests first" | **THIS SKILL** |
| "Create story tests" | **THIS SKILL** |
| "Create a NestJS module" (no TDD) | generating-nest-servers |
| "Fix this service bug" | generating-nest-servers |
| "Generate tests for existing code" | /test-generate command |
| "Build a Vue page" | developing-lt-frontend |

## Related Skills & Commands

**User-facing command:** `/lt-dev:resolve-ticket [issue-id | story-file]` — Resolves a ticket using this skill

**Works closely with:**
- `generating-nest-servers` skill - For code implementation (modules, objects, properties)
- `using-lt-cli` skill - For Git operations and project initialization
- `developing-lt-frontend` skill - For frontend E2E tests and implementation
- `coordinating-agent-teams` skill - For parallel test writing in fullstack projects
- `/lt-dev:create-ticket` command - Create any ticket type (Story, Task, Bug)
- `/lt-dev:create-story` command - Create a story, then implement with TDD
- `/lt-dev:review` command - Comprehensive quality check after implementation (Step 5a)
- `/lt-dev:backend:sec-review` command - nest-server specific security review

## TypeScript Language Server (Recommended)

**Use the LSP tool when available** for faster and more accurate code analysis:

| Operation | Use Case in TDD |
|-----------|-----------------|
| `goToDefinition` | Navigate to Controller/Service/Model definitions |
| `findReferences` | Find all usages of a method or property |
| `hover` | Get type info for parameters and return types |
| `documentSymbol` | List all methods in a Controller or Service |
| `goToImplementation` | Find Service implementations of interfaces |

**When to use LSP (especially Step 1 & 4):**
- Verifying endpoint existence → `documentSymbol` on Controller
- Finding method signatures → `hover`, `goToDefinition`
- Understanding dependencies → `findReferences`, `goToImplementation`

**Installation (if LSP not available):**
```bash
claude plugins install typescript-lsp --marketplace claude-plugins-official
```

---

## GOLDEN RULES

1. **Test through API only** — Use `testHelper.rest()` / `testHelper.graphQl()`. NEVER call Services directly or query DB in test logic. Exception: DB access only for setup/cleanup (roles, verified status).
2. **Verify before assuming** — ALWAYS read Controllers/Services/Models before writing tests. Never assume endpoints, methods, or properties exist.
3. **Failing tests are ALWAYS a problem** — Fix the root cause of every failing test, even if the failure predates the current changes or seems unrelated to the current task. A green test suite is a non-negotiable prerequisite. Never ignore, skip, or defer test failures.

**Full details: [workflow.md](${CLAUDE_SKILL_DIR}/workflow.md) -> Steps 1, 2, and 4**

---

## Core TDD Workflow - The Seven Steps

**Complete workflow details: [workflow.md](${CLAUDE_SKILL_DIR}/workflow.md)**

**Process:** Step 1 (Analysis) -> Step 2 (Create Test) -> Step 3 (Run Tests) -> [Step 3a: Fix Tests if needed] -> Step 4 (Implement) -> Step 5 (Validate) -> Step 5a (Quality Check) -> Step 5b (Final Validation)

---

### Step 1: Story Analysis & Validation
**Details: [workflow.md](${CLAUDE_SKILL_DIR}/workflow.md) -> Step 1**

- Read story, verify existing API structure (read Controllers/Resolvers)
- Document what exists vs what needs creation
- Ask for clarification if ambiguous (use AskUserQuestion)

### Step 2: Create Story Test
**Details: [workflow.md](${CLAUDE_SKILL_DIR}/workflow.md) -> Step 2**

**CRITICAL: Test through API only - NEVER direct Service/DB access!**

- Use `testHelper.rest()` or `testHelper.graphQl()`
- NEVER call Services directly or query DB in test logic
- Exception: Direct DB access ONLY for setup/cleanup (roles, verified status)

**Test Data Rules (parallel execution):**
1. Emails MUST end with `@test.com` (use: `user-${Date.now()}-${Math.random().toString(36).substring(2, 8)}@test.com`)
2. Never reuse data across test files
3. Only delete entities created in same test file
4. Implement complete cleanup in `afterAll`

### Step 3: Run Tests & Analyze
**Details: [workflow.md](${CLAUDE_SKILL_DIR}/workflow.md) -> Step 3**

```bash
# NODE_ENV=e2e is set in package.json scripts for local test execution
pnpm test  # Or: pnpm test -- tests/stories/your-story.story.test.ts
```

**Decide:** Test bugs -> Step 3a | Implementation missing -> Step 4

### Step 3a: Fix Test Errors
**Details: [workflow.md](${CLAUDE_SKILL_DIR}/workflow.md) -> Step 3a**

Fix test logic/errors. NEVER "fix" by removing security. Return to Step 3 after fixing.

### Step 4: Implement/Extend API Code
**Details: [workflow.md](${CLAUDE_SKILL_DIR}/workflow.md) -> Step 4**

**Use `generating-nest-servers` skill for:** Module/object creation, understanding existing code

**Critical Rules:**
1. **Property Descriptions:** Format as `ENGLISH (GERMAN)` when user provides German comments
2. **ServiceOptions:** Only pass what's needed (usually just `currentUser`), NOT all options
3. **Guards:** DON'T add `@UseGuards(AuthGuard(...))` - automatically activated by `@Roles()`
4. **Database indexes:** Define in @UnifiedField decorator (see `database-indexes.md`)

### Step 5: Validate & Iterate
**Details: [workflow.md](${CLAUDE_SKILL_DIR}/workflow.md) -> Step 5**

```bash
pnpm test
```

All pass -> Step 5a | Fail -> Return to Step 3

### Step 5a: Code Quality & Refactoring Check
**Details: [workflow.md](${CLAUDE_SKILL_DIR}/workflow.md) -> Step 5a**

Review: Code quality (`code-quality.md`), Database indexes (`database-indexes.md`), Security (`security-review.md`). Run `/lt-dev:review` for general security scan. Run tests after changes.

### Step 5b: Final Validation
**Details: [workflow.md](${CLAUDE_SKILL_DIR}/workflow.md) -> Step 5b**

Run all tests, verify quality checks, generate final report. DONE!

## Handling Existing Tests When Modifying Code

**Complete details: [handling-existing-tests.md](${CLAUDE_SKILL_DIR}/handling-existing-tests.md)**

**When your changes break existing tests:**
- Intentional change? -> Update tests + document why
- Unclear? -> Investigate with git (`git show HEAD`, `git diff`), fix to satisfy both old & new tests

**Remember:** Existing tests document expected behavior - preserve backward compatibility!

---

## CRITICAL: GIT COMMITS

**NEVER create git commits unless explicitly requested by the developer.**

Your responsibility:
- Create/modify files, run tests, provide comprehensive report
- **NEVER commit to git without explicit request**

You may remind in final report: "Implementation complete - review and commit when ready."

---

## CRITICAL SECURITY RULES

**Complete details: [security-review.md](${CLAUDE_SKILL_DIR}/security-review.md)**
**Extended with OWASP practices: Error Handling & Logging, Cryptographic Practices, Session & Token Management**

### NEVER:
- Remove/weaken `@Restricted()` or `@Roles()` decorators
- Modify `securityCheck()` to bypass security
- Add `@UseGuards(AuthGuard(...))` manually (automatically activated by `@Roles()`)

### ALWAYS:
- Analyze existing security before writing tests
- Create appropriate test users with correct roles
- Test with least-privileged users
- Ask before changing ANY security decorator

**When tests fail due to security:** Create proper test users with appropriate roles, NEVER remove security decorators.

## Code Quality Standards

**Complete details: [code-quality.md](${CLAUDE_SKILL_DIR}/code-quality.md)**

**Must follow:**
- File organization, naming conventions, import statements from existing code
- Error handling and validation patterns
- Use @lenne.tech/nest-server first, add packages as last resort

**Test quality:**
- 80-100% coverage, self-documenting, independent, repeatable, fast

**NEVER use `declare` keyword** - it prevents decorators from working!

## Autonomous Execution

**Work autonomously:** Create tests, run tests, fix code, iterate Steps 3-5, use nest-server-generator skill

**Only ask when:** Story ambiguous, security changes needed, new packages, architectural decisions, persistent failures

## Final Report

When all tests pass, provide comprehensive report including:
- Story name, tests created (location, count, coverage)
- Implementation summary (modules/objects/properties created/modified)
- Test results (all passing, scenarios summary)
- Code quality (patterns followed, security preserved, dependencies, refactoring, indexes)
- Security review (auth/authz, validation, data exposure, ownership, injection prevention, errors, security tests)
- Files modified (with changes description)
- `/lt-dev:review` results (general security scan findings)
- Next steps (recommendations)

## Common Patterns

**Complete patterns and examples: [examples.md](${CLAUDE_SKILL_DIR}/examples.md) and [reference.md](${CLAUDE_SKILL_DIR}/reference.md)**

**Study existing tests first!** Common patterns:
- Create test users via `/auth/signin`, set roles/verified via DB
- REST requests: `testHelper.rest('/api/...', { method, payload, token, statusCode })`
- GraphQL queries: `testHelper.graphQl({ name, type, arguments, fields }, { token })`
- Test organization: `describe` blocks for Happy Path, Error Cases, Edge Cases

## Integration with generating-nest-servers

**During Step 4 (Implementation), use `generating-nest-servers` skill for:**
- Module creation (`lt server module`)
- Object creation (`lt server object`)
- Adding properties (`lt server addProp`)
- Understanding existing code (Services, Controllers, Resolvers, Models, DTOs)

**Best Practice:** Invoke skill for NestJS component work rather than manual editing.

---
> Converted and distributed by [TomeVault](https://tomevault.io/claim/lennetech) — claim your Tome and manage your conversions.
<!-- tomevault:4.0:skill_md:2026-04-14 -->

