test-driven-development
Use this skill when implementing any feature, bug fix, or plan task. Triggers on "write tests", "add a test", "do TDD", "test-driven", "implement with tests", "implement task", or when dispatched as a subagent for plan execution. Write test first, watch it fail, write minimal code to pass.
What this skill does
# Test-Driven Development (TDD)
Write the test first. Watch it fail. Write minimal code to pass.
If you wrote implementation code before the test, discard it and start fresh from the test.
## The Cycle: Red → Green → Refactor
### RED — Write Failing Test
Write one minimal test showing what should happen.
**Good:**
```typescript
test("retries failed operations 3 times", async () => {
let attempts = 0;
const operation = () => {
attempts++;
if (attempts < 3) throw new Error("fail");
return "success";
};
const result = await retryOperation(operation);
expect(result).toBe("success");
expect(attempts).toBe(3);
});
```
Clear name, tests real behavior, one thing.
**Bad:**
```typescript
test("retry works", async () => {
const mock = jest
.fn()
.mockRejectedValueOnce(new Error())
.mockRejectedValueOnce(new Error())
.mockResolvedValueOnce("success");
await retryOperation(mock);
expect(mock).toHaveBeenCalledTimes(3);
});
```
Vague name, tests mock not code.
Requirements:
- One behavior per test
- Clear name describing behavior
- Real code (mocks only if unavoidable)
### Verify RED — Run and Confirm Failure
```bash
npm test path/to/test.test.ts
```
Confirm:
- Test fails (not errors from typos)
- Failure is because the feature is missing
- If test passes immediately: you're testing existing behavior — fix the test
### GREEN — Minimal Code
Write the simplest code to pass the test. Nothing more.
**Good:**
```typescript
async function retryOperation<T>(fn: () => Promise<T>): Promise<T> {
for (let i = 0; i < 3; i++) {
try {
return await fn();
} catch (e) {
if (i === 2) throw e;
}
}
throw new Error("unreachable");
}
```
**Bad:**
```typescript
async function retryOperation<T>(
fn: () => Promise<T>,
options?: {
maxRetries?: number;
backoff?: "linear" | "exponential";
onRetry?: (attempt: number) => void;
}
): Promise<T> { /* YAGNI */ }
```
Don't add features, refactor other code, or "improve" beyond the test.
### Verify GREEN — Run and Confirm Pass
```bash
npm test path/to/test.test.ts
```
Confirm: test passes, other tests still pass, output clean.
If test fails: fix code, not test. If other tests fail: fix now.
### REFACTOR — Clean Up (Green Only)
Remove duplication, improve names, extract helpers. Keep tests green.
### Repeat
Next failing test for next behavior.
## Why Test-First Matters
Tests written after code pass immediately — proving nothing. You never see them catch the bug they're supposed to catch. Test-first forces you to see the failure, proving the test actually validates behavior.
Tests-after are biased by your implementation: you test what you built, not what's required. Tests-first force edge case discovery before implementing.
If the test is hard to write, the design is telling you something — the interface is too complex.
## Good Tests
| Quality | Good | Bad |
|---------|------|-----|
| Minimal | One thing per test | `test('validates email and domain and whitespace')` |
| Clear | Name describes behavior | `test('test1')` |
| Shows intent | Demonstrates desired API | Obscures what code should do |
| Real code | Tests actual behavior | Tests mock behavior |
## When Stuck
| Problem | Solution |
|---------|----------|
| Don't know how to test | Write wished-for API. Write assertion first. |
| Test too complicated | Design too complicated. Simplify interface. |
| Must mock everything | Code too coupled. Use dependency injection. |
| Test setup huge | Extract helpers. Still complex? Simplify design. |
## Bug Fix Example
**Bug:** Empty email accepted
**RED:**
```typescript
test("rejects empty email", async () => {
const result = await submitForm({ email: "" });
expect(result.error).toBe("Email required");
});
```
**Verify RED:** `FAIL: expected 'Email required', got undefined`
**GREEN:**
```typescript
function submitForm(data: FormData) {
if (!data.email?.trim()) {
return { error: "Email required" };
}
// ...
}
```
**Verify GREEN:** `PASS`
**REFACTOR:** Extract validation for multiple fields if needed.
## Verification Checklist
Before marking work complete:
- [ ] Every new function has a test
- [ ] Watched each test fail before implementing
- [ ] Each test failed for expected reason (feature missing, not typo)
- [ ] Wrote minimal code to pass each test
- [ ] All tests pass, output clean
- [ ] Tests use real code (mocks only if unavoidable)
- [ ] Edge cases and errors covered
## Integration
- **testing-anti-patterns** — reviewing existing test quality
- **systematic-debugging** — write failing test reproducing bug
- **verification-before-completion** — verify tests pass before claiming done
Related in Productivity
gitea-workflow
IncludedOrchestrate agile development workflows for Gitea repositories using the tea CLI. Use when working with Gitea-hosted repos and asking to 'run the workflow', 'continue working', 'what's next', 'complete the task cycle', 'start my day', 'end the sprint', 'implement the next task', or wanting guided step-by-step development assistance. Keywords: workflow, orchestrate, agile, task cycle, sprint, daily, implement, review, PR, standup, retrospective, gitea, tea.
microsoft-graph-gateway
IncludedRoute Microsoft Graph work in this workspace. Use when users want to read or write Outlook mail, calendar events, contacts, OneDrive or SharePoint files, Teams, Planner, To Do, users, groups, directory data, or arbitrary Microsoft Graph endpoints from VS Code. Prefer WorkIQ for common read scenarios. Use Microsoft Graph for write actions and gap-read scenarios that need exact Graph properties, filters, permissions, or endpoints.
copilotkit
IncludedUse when building with CopilotKit — setup, development, integrations, debugging, upgrading, or contributing. Routes to the appropriate specialized skill based on the task.
wordly-wisdom
IncludedProvides calibrated decision analysis using Charlie Munger-style multiple mental models, inversion, incentive mapping, circle-of-competence checks, misjudgment audits, second-order effects, and forecast updates. Use when the user asks for an oracle take, a hard call, a decision memo, a premortem, an outside view, a red-team, a sanity-check, what am I missing, think this through, or wants a strategy, hire, investment, plan, product, partnership, or major life choice analysed. Avoid for simple factual lookups or time-sensitive legal, medical, or market questions without fresh evidence.
swain-session
IncludedSession management and project status dashboard. Owns the full session lifecycle (start/work/close/resume), focus lane, bookmarks, worktree detection, and tab naming. Also serves as the project status dashboard — shows active epics, progress, actionable next steps, blocked items, tasks, GitHub issues, and recommendations. Worktree creation is deferred to swain-do task dispatch (SPEC-195). Triggers on: 'session', 'status', 'what's next', 'dashboard', 'overview', 'where are we', 'what should I work on', 'show me priorities', 'bookmark', 'focus on', 'session info'.
gandi
IncludedComprehensive Gandi domain registrar integration for domain and DNS management. Register and manage domains, create/update/delete DNS records (A, AAAA, CNAME, MX, TXT, SRV, and more), configure email forwarding and aliases, check SSL certificate status, create DNS snapshots for safe rollback, bulk update zone files, and monitor domain expiration. Supports multi-domain management, zone file import/export, and automated DNS backups. Includes both read-only and destructive operations with safety controls.