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) |
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

Vercel Analytics & Speed Insights Setup

Wire up Vercel Analytics, Speed Insights, and SPA routing rewrites into a React/Vite project in one pass — including the routing fix most people miss.

5 minutes
Beginner
Developer Tools

Unslop UI: Kill the AI Design Tells

A frontend guardrail built from a 3.2M-post Reddit analysis of what people actually call AI slop, with a build mode that forces design decisions up front and an audit mode that scans existing code for the tells

10 minutes
Intermediate
Developer Tools

Tunnel Doctor

Diagnose and fix conflicts between Tailscale and proxy/VPN tools on macOS — route hijacking, proxy env vars, SSH double-tunneling, and the ~60s DNS resolver stall.

15 minutes
Advanced
Developer Tools

Vibe Coder: Idea to Prototype

Describe what you want to build and get clean, working code with a simple approach explanation, setup instructions, and optional improvements — optimized for shipping over perfecting.

5 minutes
Beginner
Developer Tools

Who Built This Before Me

Check whether your project, tool, library, or product idea has already been built — before you invest a weekend or a quarter in it.

5 minutes
Intermediate
Developer Tools

Vibe Skill Creator

Build world-class Claude skills through a guided 10-step conversation — explore where Claude fails by default, research the domain, draft, self-critique, test on a real scenario, and iterate until the skill actually improves output.

10 minutes
Intermediate
Developer Tools

Twilio SMS Integration

Automate SMS communications, two-way messaging, notifications, and voice workflows with Twilio

10 minutes
Advanced
Developer Tools

Webhook Automation Builder

Build and manage webhook-based integrations for real-time event processing and API connections

10 minutes
Advanced
Developer Tools

Web App Testing

Test local web applications with Playwright automation for frontend verification, UI debugging, and screenshot capture.

15 minutes
Intermediate
Developer Tools

Tech Debt Analyzer

Identify, analyze, document, and track technical debt in JavaScript/TypeScript codebases with automated detection and prioritized remediation plans.

10 minutes
Intermediate
Developer Tools

Agent SDK App Builder

Scaffold new Claude Agent SDK applications in TypeScript or Python, and verify existing ones against official SDK patterns before you ship.

10 minutes
Intermediate
Developer Tools

AI Agent Builder

Build AI agents with tools, memory, and multi-step reasoning - ChatGPT, Claude, Gemini integration patterns

10 minutes
Advanced

Browse all Developer Tools playbooks →