testing-workflows
# Claude Code Testing Workflows
What this skill does
# Claude Code Testing Workflows
Complete guide to testing patterns, TDD, and test execution within Claude Code.
## Test Execution
### Running Tests
```bash
# Common test commands
npm test
pnpm test
yarn test
bun test
pytest
go test ./...
cargo test
# Single test file
npm test -- path/to/test.ts
pytest path/to/test.py
# Pattern matching
npm test -- --grep "authentication"
pytest -k "test_auth"
# Watch mode
npm test -- --watch
pytest --watch
```
### Claude's Testing Protocol
1. **Before committing**: Always run relevant tests
2. **After implementing**: Run tests to verify
3. **When debugging**: Run specific failing test first
4. **TDD approach**: Write test → run (fail) → implement → run (pass)
## Test-Driven Development (TDD) Pattern
### Step 1: Write the Test First
```typescript
// auth.test.ts
describe('authenticateUser', () => {
it('should return user for valid credentials', async () => {
const result = await authenticateUser('[email protected]', 'password123');
expect(result).toMatchObject({
id: expect.any(String),
email: '[email protected]',
});
});
it('should throw for invalid credentials', async () => {
await expect(
authenticateUser('[email protected]', 'wrong')
).rejects.toThrow('Invalid credentials');
});
});
```
### Step 2: Run Test (Expect Failure)
```bash
npm test -- auth.test.ts
# FAIL: authenticateUser is not defined
```
### Step 3: Implement
```typescript
// auth.ts
export async function authenticateUser(email: string, password: string) {
const user = await db.user.findUnique({ where: { email } });
if (!user || !await bcrypt.compare(password, user.passwordHash)) {
throw new Error('Invalid credentials');
}
return { id: user.id, email: user.email };
}
```
### Step 4: Run Test (Expect Pass)
```bash
npm test -- auth.test.ts
# PASS
```
## Using Test-Writer Agent
Claude Code has a specialized test-writing agent:
```
Agent(
subagent_type="test-writer",
prompt="Write comprehensive tests for the authentication module in src/auth/",
description="Write auth tests"
)
```
The test-writer agent:
- Reads the source code
- Identifies all functions/methods to test
- Generates test files with edge cases
- Handles mocking external dependencies
- Follows project test conventions
## Test Types
### Unit Tests
```typescript
// Test individual functions in isolation
describe('calculateTotal', () => {
it('sums items correctly', () => {
expect(calculateTotal([10, 20, 30])).toBe(60);
});
it('handles empty array', () => {
expect(calculateTotal([])).toBe(0);
});
it('handles negative values', () => {
expect(calculateTotal([10, -5])).toBe(5);
});
});
```
### Integration Tests
```typescript
// Test multiple components together
describe('POST /api/auth/login', () => {
it('returns JWT for valid login', async () => {
const res = await request(app)
.post('/api/auth/login')
.send({ email: '[email protected]', password: 'pass123' });
expect(res.status).toBe(200);
expect(res.body.token).toBeDefined();
});
});
```
### End-to-End Tests
```typescript
// Test full user flows
describe('User Registration Flow', () => {
it('allows user to register and login', async () => {
// Register
await page.goto('/register');
await page.fill('#email', '[email protected]');
await page.fill('#password', 'secure123');
await page.click('button[type="submit"]');
// Verify redirect to dashboard
await expect(page).toHaveURL('/dashboard');
});
});
```
## Test Frameworks
### JavaScript/TypeScript
| Framework | Command | Config |
|-----------|---------|--------|
| Jest | `npx jest` | `jest.config.js` |
| Vitest | `npx vitest` | `vitest.config.ts` |
| Mocha | `npx mocha` | `.mocharc.yml` |
| Playwright | `npx playwright test` | `playwright.config.ts` |
| Cypress | `npx cypress run` | `cypress.config.js` |
### Python
| Framework | Command | Config |
|-----------|---------|--------|
| pytest | `pytest` | `pytest.ini` / `pyproject.toml` |
| unittest | `python -m unittest` | N/A |
### Other
| Language | Framework | Command |
|----------|-----------|---------|
| Go | testing | `go test ./...` |
| Rust | built-in | `cargo test` |
| Java | JUnit | `mvn test` / `gradle test` |
## Test Best Practices in Claude Code
1. **Write tests alongside code** — Not as an afterthought
2. **Descriptive names** — `it('should return 404 for non-existent user')` not `it('test 1')`
3. **Prefer real implementations** — Over excessive mocking
4. **Test edge cases** — Empty inputs, null values, boundary conditions
5. **Keep tests fast** — Mock external services, use in-memory databases
6. **One assertion per test** — When possible, for clear failure messages
7. **Run before commit** — Claude always runs tests before committing (when asked)
## Coverage
```bash
# JavaScript/TypeScript
npx jest --coverage
npx vitest --coverage
npx c8 npm test
# Python
pytest --cov=src --cov-report=html
# Go
go test -coverprofile=coverage.out ./...
```
## Debugging Failing Tests
Claude's approach to test failures:
1. Read the test file and understand intent
2. Read the error message carefully
3. Read the source code being tested
4. Identify the discrepancy
5. Fix either the test (if expectations are wrong) or the code (if logic is wrong)
6. Re-run the specific failing test
7. Run full test suite to check for regressions
Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.