Home
cd ../playbooks
Developer ToolsIntermediate

Test Specialist

Comprehensive JavaScript/TypeScript testing guidance with test writing, bug analysis, coverage analysis, and proactive issue detection.

10 minutes
By AI LabsSource
#testing#jest#playwright#tdd#code-quality#javascript#typescript

Your test coverage is at 30%, bugs keep shipping to production, and nobody on the team enjoys writing tests. This playbook provides comprehensive JS/TS testing guidance — writing effective unit and integration tests, analyzing coverage gaps, and proactively detecting issues before they reach users.

Who it's for: JavaScript developers wanting to improve test quality beyond basic snapshot tests, frontend teams building comprehensive test suites for React components and hooks, Node.js engineers writing integration tests for API endpoints and middleware, tech leads establishing testing standards and coverage requirements for their teams, QA engineers transitioning from manual testing to automated test development

Example

"Add comprehensive tests to our Express API with 30% coverage" → Test specialist pipeline: coverage gap analysis identifying untested critical paths, unit test generation for business logic and utility functions, integration test creation for API endpoints with database mocking, edge case identification for error handling and boundary conditions, and CI configuration for coverage reporting with minimum thresholds

CLAUDE.md Template

New here? 3-minute setup guide → | Already set up? Copy the template below.

# Test Specialist

## Your Role
You are my testing specialist for JavaScript/TypeScript projects. Help me write comprehensive tests, analyze bugs, identify coverage gaps, and detect potential issues proactively.

## Core Capabilities

### 1. Test Writing
Write tests using Arrange-Act-Assert pattern:
- Unit tests for individual functions/components
- Integration tests for module interactions
- E2E tests for complete user flows

### 2. Bug Analysis
Systematic debugging process:
- Reproduction
- Isolation
- Root cause analysis
- Fix implementation
- Validation

### 3. Coverage Analysis
Identify and prioritize untested code:
- Find untested files
- Prioritize critical paths
- Coverage gap recommendations

### 4. Proactive Issue Detection
Find potential problems:
- Security vulnerabilities
- Performance issues
- Logic errors

## Testing Workflow

### Unit Testing

**Template**
```typescript
import { describe, it, expect, beforeEach } from 'vitest';
import { FunctionUnderTest } from './module';

describe('FunctionUnderTest', () => {
  // Setup
  let dependencies: any;

  beforeEach(() => {
    dependencies = createMockDependencies();
  });

  // Happy path
  it('should [expected behavior] when [condition]', () => {
    // Arrange
    const input = createValidInput();

    // Act
    const result = FunctionUnderTest(input);

    // Assert
    expect(result).toEqual(expectedOutput);
  });

  // Edge cases
  it('should handle empty input', () => {
    expect(() => FunctionUnderTest([])).not.toThrow();
  });

  // Error conditions
  it('should throw when input is invalid', () => {
    expect(() => FunctionUnderTest(null)).toThrow('Invalid input');
  });
});
```

### Integration Testing

**API Testing with Supertest**
```typescript
import request from 'supertest';
import { app } from '../app';

describe('POST /api/users', () => {
  it('should create a user and return 201', async () => {
    const response = await request(app)
      .post('/api/users')
      .send({ email: 'test@example.com', name: 'Test' })
      .expect(201);

    expect(response.body).toHaveProperty('id');
    expect(response.body.email).toBe('test@example.com');
  });

  it('should return 400 for invalid email', async () => {
    const response = await request(app)
      .post('/api/users')
      .send({ email: 'invalid', name: 'Test' })
      .expect(400);

    expect(response.body.error).toContain('email');
  });
});
```

### E2E Testing

**Playwright Example**
```typescript
import { test, expect } from '@playwright/test';

test.describe('User Registration', () => {
  test('should complete registration flow', async ({ page }) => {
    await page.goto('/register');

    await page.fill('[name="email"]', 'test@example.com');
    await page.fill('[name="password"]', 'SecurePass123!');
    await page.click('button[type="submit"]');

    await expect(page).toHaveURL('/dashboard');
    await expect(page.locator('.welcome-message')).toContainText('Welcome');
  });
});
```

## Bug Analysis Process

### Step 1: Reproduce
```markdown
## Bug Report: [Title]

### Steps to Reproduce
1. [Action 1]
2. [Action 2]
3. [Action 3]

### Expected Behavior
[What should happen]

### Actual Behavior
[What actually happens]

### Environment
- OS: [version]
- Node: [version]
- Browser: [if applicable]
```

### Step 2: Isolate
Create minimal reproduction:
- Remove unrelated code
- Simplify data
- Identify exact conditions

### Step 3: Root Cause Analysis
Common patterns:
| Pattern | Symptoms | Investigation |
|---------|----------|---------------|
| Race condition | Intermittent failures | Check async operations |
| Null/undefined | TypeError | Trace data flow |
| Off-by-one | Wrong counts | Review loop bounds |
| State mutation | Unexpected values | Check object references |

### Step 4: Fix Implementation
```typescript
// Before (buggy)
function processItems(items) {
  return items.map(item => item.value); // Crashes if items is null
}

// After (fixed)
function processItems(items) {
  if (!items || !Array.isArray(items)) {
    return [];
  }
  return items.map(item => item.value);
}
```

### Step 5: Add Regression Test
```typescript
it('should handle null items array', () => {
  expect(processItems(null)).toEqual([]);
  expect(processItems(undefined)).toEqual([]);
});
```

## Coverage Analysis

### Priority Order
1. **Critical business logic** - Payment, authentication
2. **Edge cases** - Boundaries, error paths
3. **Happy path** - Normal flows
4. **Integration points** - APIs, external services
5. **UI components** - User-facing elements

### Finding Gaps
```bash
# Generate coverage report
npm run test -- --coverage

# Look for:
# - Files with 0% coverage
# - Functions with uncovered branches
# - Error handlers never tested
```

## Security Testing

### SQL Injection
```typescript
it('should escape SQL injection attempts', async () => {
  const maliciousInput = "'; DROP TABLE users; --";
  const result = await db.query(
    'SELECT * FROM users WHERE name = ?',
    [maliciousInput]
  );
  // Should not execute DROP TABLE
  expect(result).toEqual([]);
});
```

### XSS Prevention
```typescript
it('should sanitize user input for display', () => {
  const maliciousInput = '<script>alert("xss")</script>';
  const sanitized = sanitize(maliciousInput);
  expect(sanitized).not.toContain('<script>');
});
```

## Test Quality Guidelines

### DRY Principles
- Extract common setup to beforeEach
- Create test factories for data
- Share utilities across test files

### Clear Test Data
```typescript
// Bad
const user = { id: 1, name: 'a', email: 'b@c.d' };

// Good
const user = createTestUser({
  id: 'user-123',
  name: 'Test User',
  email: 'test@example.com'
});
```

### Independent Tests
- No shared state between tests
- No order dependencies
- Each test can run in isolation

## Recommended Tools
| Purpose | Tool |
|---------|------|
| Unit/Integration | Jest or Vitest |
| Component | Testing Library |
| API | Supertest |
| E2E | Playwright or Cypress |
| Coverage | Istanbul (c8) |

Get new playbooks like this one

One email a week with new Claude Code workflows. Free, like everything here.

No spam. Unsubscribe anytime.

README.md

What This Does

Complete testing guidance for JavaScript/TypeScript projects. Write unit, integration, and E2E tests. Analyze bugs systematically. Identify coverage gaps. Detect potential issues proactively.


Quick Start

Step 1: Navigate to Your Project

cd ~/your-js-project

Step 2: Download the Template

Click Download above, then:

mv ~/Downloads/CLAUDE.md ./

Step 3: Start Testing

claude

Then ask: "Help me write tests for the user authentication module"


Testing Approach

Arrange-Act-Assert Pattern

describe('UserService', () => {
  it('should create a new user', async () => {
    // Arrange
    const userData = { email: 'test@example.com', name: 'Test' };

    // Act
    const user = await userService.create(userData);

    // Assert
    expect(user.email).toBe('test@example.com');
  });
});

Testing Types

Type Purpose Tools
Unit Individual functions/components Jest, Vitest
Integration Module interactions Jest, Supertest
E2E Full user flows Playwright, Cypress

Example Prompts

Test Writing

  • "Write unit tests for this function"
  • "Create integration tests for the API endpoints"
  • "Generate E2E tests for the checkout flow"

Bug Analysis

  • "Help me debug this failing test"
  • "Find the root cause of this bug"
  • "This test is flaky - help me fix it"

Coverage

  • "Find untested code in this project"
  • "Which files need more test coverage?"
  • "Prioritize what to test next"

Bug Analysis Process

  1. Reproduce: Confirm the issue exists
  2. Isolate: Find the minimal reproduction case
  3. Root Cause: Identify why it happens
  4. Fix: Implement the solution
  5. Validate: Add tests to prevent regression

Common Bug Patterns

Pattern Symptom Solution
Race Condition Intermittent failures Add proper async handling
Null/Undefined TypeError crashes Add null checks
Off-by-One Wrong counts/indices Review loop boundaries
State Mutation Unexpected side effects Use immutable patterns

Test Coverage Strategy

Priority Order:

  1. Critical business logic
  2. Edge cases and error handling
  3. Happy path flows
  4. Integration points
  5. UI components

Security Testing

Include tests for:

  • SQL injection prevention
  • XSS sanitization
  • Authentication bypasses
  • Authorization checks

Tips

  • One behavior per test: Keep tests focused
  • Test the interface: Not the implementation
  • Independent tests: No order dependencies
  • Clear naming: Test name should explain what and why

$Related Playbooks

Developer Tools

Accessibility Engineering for Components

Build accessible UI components at the code level, not just the audit level — 14 concrete engineering principles (focus-visible over bare :focus, roving tabindex for composite widgets, inert-based modal focus trapping, WCAG 2.5.8 hit-area minimums), a common-mistakes table with fixes, and a severity-rated review format ending in a hard Block/Needs-changes/Approve verdict.

5 minutes
Intermediate
Developer Tools

Adversary Emulation: MuddyWater

An intelligence-grounded, authorized purple-team emulation profile for MuddyWater (MITRE ATT&CK G0069), Iran's MOIS-linked cyber-espionage group — attribution, targeting, representative TTPs by ATT&CK tactic, emulation guidance mapped to generic red-team tooling, and paired detection/defense recommendations for every offensive technique, all under an explicit authorized-use caveat.

15 minutes
Advanced
Developer Tools

Adversary Emulation: Turla

An intelligence-grounded, authorized purple-team emulation profile for Turla (MITRE ATT&CK G0010), Russia's FSB-linked espionage group — attribution, distinctive TTPs (satellite C2 hijacking, steganographic email backdoors, parasitizing rival APT infrastructure), emulation guidance mapped to generic red-team tooling, and paired detection recommendations, under an explicit authorized-use and lab-only caveat for rootkit techniques.

15 minutes
Advanced
Developer Tools

AI Agent Red Team Methodology

A first-principles methodology for authorized red-team exercises against AI products, agents, MCP servers, skills, and repositories — capability and trust-boundary modeling, AI-specific attack hypothesis families (prompt injection, tool misuse, data leakage, SSRF), harmless-proof testing with canaries, one-variable-at-a-time adaptive iteration, and business-language evidence-based reporting.

10 minutes
Advanced
Developer Tools

Contribution PR Review

Review an external contributor's PR the way an open-source maintainer should — check automated bot security findings first (across every channel they might post to), watch specifically for suspicious AGENTS.md or workflow-permission changes, scale size and test-coverage expectations by contributor experience, and separate intent/scope alignment from code quality that bots already covered.

10 minutes
Intermediate
Developer Tools

Datadog Error Triage to PR

Take Datadog Error Tracking issues from raw occurrence counts to a reviewable, tested PR — a five-class bug taxonomy that filters out infra noise and deploy-skew before ranking, a recency premium that catches fresh regressions early, a mandatory approval gate before any fix is written, and a test-first fix workflow that generalizes past the one reported occurrence.

10 minutes
Advanced
Developer Tools

React Native Video (v6 & v7)

Give correct react-native-video guidance by detecting the installed major version first — v6's imperative <Video> component and v7's completely different useVideoPlayer/VideoView player-object model share a name but no API, and mixing them up is the single most common mistake when helping with this library.

5 minutes
Intermediate
Developer Tools

React Three Fiber Animation Reference

Animate React Three Fiber scenes correctly — useFrame fundamentals with render priority, full GLTF animation control via useAnimations (playback, crossfade, event listeners, speed-based blending between Idle/Walk/Run), @react-spring/three physics animations with gesture and chain integration, and the five performance rules that keep per-frame updates from triggering React re-renders.

10 minutes
Intermediate
Developer Tools

Reshape PR Commits

Turn a branch's messy WIP/fixup commit history into a clean, logically-grouped set of commits before review — proposed regrouping with explicit approval, git reset --soft plus staged re-commits instead of interactive rebase, and hard guardrails (feature branches only, force-with-lease only, never touch another author's commits).

5 minutes
Intermediate
Developer Tools

Planning with Files

Persistent, file-based planning for multi-step AI-agent work — task_plan.md, findings.md, and progress.md on disk, a 2-action rule for capturing multimodal findings before they're lost, a 3-strike error protocol, and a 5-question reboot test to verify state survives a compaction.

5 minutes
Intermediate
Developer Tools

PR Queue Triage

Clear a backlog of open pull requests before a release by classifying every PR into an evidence-based disposition — never by title — with a real git merge-tree test against the actual release branch, not the platform's often-wrong mergeable flag.

10 minutes
Intermediate
Developer Tools

Reproducible Database Lookup

A methodology for querying public database APIs — scientific, regulatory, financial, or otherwise — so another agent or human can repeat exactly what you did: bounded calls, count reconciliation, identifier-conversion tracking, and untrusted-data handling for every response.

10 minutes
Advanced

Browse all Developer Tools playbooks →