Claude
Skills
Sign in
Back

Frontend Testing

Included with Lifetime
$97 forever

Comprehensive frontend testing patterns including component tests (Jest/Vitest + RTL), visual regression (Playwright), accessibility (axe-core), and performance (Lighthouse) testing for React/Next.js applications. Use when building frontend tests, testing React components, implementing visual regression, running accessibility tests, performance testing, or when user mentions component testing, visual regression, a11y testing, React Testing Library, Jest, Vitest, Lighthouse, or frontend testing.

Designscripts

What this skill does


# Frontend Testing

**CRITICAL: The description field above controls when Claude auto-loads this skill.**

## Overview

Provides comprehensive frontend testing patterns for React/Next.js applications including:
- Component testing with Jest/Vitest + React Testing Library
- Visual regression testing with Playwright
- Accessibility testing with axe-core
- Performance testing with Lighthouse
- Test infrastructure setup and configuration
- Coverage analysis and reporting

## Security Requirements

All code examples and templates in this skill follow strict security rules:

**CRITICAL:** Reference @docs/security/SECURITY-RULES.md

- Placeholders only, never real credentials
- Environment variable references in code
- `.gitignore` protection for secrets
- Setup documentation for key acquisition

## Instructions

### 1. Initialize Frontend Test Infrastructure

Use `scripts/init-frontend-tests.sh` to set up comprehensive frontend testing:

```bash
bash scripts/init-frontend-tests.sh [project-path]
```

This will:
- Detect testing framework (Jest or Vitest)
- Install React Testing Library dependencies
- Install Playwright for visual regression
- Install axe-core for accessibility testing
- Install Lighthouse for performance testing
- Create test configuration files
- Set up test utilities and helpers
- Create initial test examples

### 2. Run Component Tests

Use `scripts/run-component-tests.sh` to execute component tests:

```bash
bash scripts/run-component-tests.sh [test-pattern] [options]
```

Options:
- Test pattern: Specific test file or glob pattern
- Options: --coverage, --watch, --updateSnapshot

This will:
- Run Jest or Vitest tests
- Execute React Testing Library tests
- Generate coverage reports
- Report pass/fail status

### 3. Run Visual Regression Tests

Use `scripts/run-visual-regression.sh` for visual testing:

```bash
bash scripts/run-visual-regression.sh [test-pattern] [update-snapshots]
```

This will:
- Run Playwright visual regression tests
- Compare against baseline snapshots
- Generate diff images for failures
- Update snapshots if requested
- Mask dynamic content automatically

### 4. Run Accessibility Tests

Use `scripts/run-accessibility-tests.sh` for a11y testing:

```bash
bash scripts/run-accessibility-tests.sh [test-pattern]
```

This will:
- Run axe-core accessibility tests via Playwright
- Check ARIA attributes
- Validate keyboard navigation
- Test color contrast
- Report WCAG violations

### 5. Run Performance Tests

Use `scripts/run-performance-tests.sh` for performance testing:

```bash
bash scripts/run-performance-tests.sh [url] [options]
```

This will:
- Run Lighthouse audits
- Check Core Web Vitals (LCP, FID, CLS)
- Analyze bundle size
- Monitor render performance
- Generate performance reports

### 6. Generate Coverage Report

Use `scripts/generate-coverage-report.sh` to aggregate coverage:

```bash
bash scripts/generate-coverage-report.sh [output-dir]
```

This will:
- Aggregate coverage from all test types
- Generate HTML coverage report
- Calculate coverage percentages
- Identify untested files
- Report coverage by test type

## Available Scripts

- **init-frontend-tests.sh**: Initialize complete frontend testing infrastructure
- **run-component-tests.sh**: Execute Jest/Vitest component tests
- **run-visual-regression.sh**: Execute Playwright visual regression tests
- **run-accessibility-tests.sh**: Execute axe-core accessibility tests
- **run-performance-tests.sh**: Execute Lighthouse performance tests
- **generate-coverage-report.sh**: Aggregate coverage data and generate reports

## Templates

### Configuration Files
- **jest.config.js**: Jest configuration for React/Next.js
- **vitest.config.ts**: Vitest configuration for React/Next.js
- **test-utils.ts**: Shared test utilities and custom renderers
- **playwright.visual.config.ts**: Playwright config for visual regression
- **playwright.a11y.config.ts**: Playwright config for accessibility testing

### Test Templates
- **component-test.spec.tsx**: Component test template with RTL
- **visual-regression.spec.ts**: Visual regression test template
- **accessibility.spec.ts**: Accessibility test template
- **performance.spec.ts**: Performance test template with Lighthouse

### Utility Templates
- **setup-tests.ts**: Test setup and global mocks
- **test-helpers.ts**: Custom test helper functions
- **mock-factories.ts**: Mock data factories

## Examples

- **button-component-test.tsx**: Real component test for Button component
- **login-page-visual.spec.ts**: Real visual regression test for login page
- **form-accessibility.spec.ts**: Real accessibility test for form components
- **homepage-performance.spec.ts**: Real performance test for homepage

## Component Testing Patterns

### React Testing Library Pattern
```typescript
import { render, screen, userEvent } from '@testing-library/react';
import { Button } from './Button';

test('renders and handles click', async () => {
  const handleClick = jest.fn();
  render(<Button onClick={handleClick}>Click me</Button>);

  const button = screen.getByRole('button', { name: /click me/i });
  await userEvent.click(button);

  expect(handleClick).toHaveBeenCalledTimes(1);
});
```

### Testing Patterns
- **Rendering**: Use render() from RTL
- **Querying**: Prefer getByRole, getByText, getByLabelText
- **User Interaction**: Use userEvent for realistic interactions
- **Assertions**: Assert on visible behavior, not implementation
- **Async**: Use waitFor for async operations

## Visual Regression Testing Patterns

### Baseline Creation
```typescript
import { test, expect } from '@playwright/test';

test('homepage visual regression', async ({ page }) => {
  await page.goto('http://localhost:3000');
  await page.waitForLoadState('networkidle');

  // Mask dynamic content
  await page.locator('.timestamp').evaluate(el => el.style.visibility = 'hidden');

  await expect(page).toHaveScreenshot('homepage.png');
});
```

### Best Practices
- Create stable baselines
- Use consistent viewport sizes
- Mask dynamic content (dates, random IDs, animations)
- Wait for network idle
- Test critical user paths

## Accessibility Testing Patterns

### axe-core Integration
```typescript
import { test, expect } from '@playwright/test';
import { injectAxe, checkA11y } from 'axe-playwright';

test('form accessibility', async ({ page }) => {
  await page.goto('http://localhost:3000/form');
  await injectAxe(page);

  await checkA11y(page, null, {
    detailedReport: true,
    detailedReportOptions: {
      html: true
    }
  });
});
```

### WCAG Compliance
- Check ARIA attributes
- Validate keyboard navigation (Tab, Enter, Escape)
- Test screen reader compatibility
- Verify color contrast
- Ensure focus management

## Performance Testing Patterns

### Lighthouse Integration
```typescript
import { test } from '@playwright/test';
import { playAudit } from 'playwright-lighthouse';

test('homepage performance', async ({ page }) => {
  await page.goto('http://localhost:3000');

  await playAudit({
    page,
    thresholds: {
      performance: 90,
      accessibility: 90,
      'best-practices': 90,
      seo: 90,
      'first-contentful-paint': 2000,
      'largest-contentful-paint': 3000,
      'cumulative-layout-shift': 0.1,
    },
    port: 9222,
  });
});
```

### Core Web Vitals
- **LCP**: Largest Contentful Paint < 2.5s
- **FID**: First Input Delay < 100ms
- **CLS**: Cumulative Layout Shift < 0.1
- **TTFB**: Time to First Byte < 800ms

## Test Organization

### Directory Structure
```
tests/
├── unit/                    # Component unit tests
│   ├── Button.spec.tsx
│   └── Form.spec.tsx
├── integration/             # Component integration tests
│   └── AuthFlow.spec.tsx
├── visual/                  # Visual regression tests
│   ├── homepage.spec.ts
│   └── dashboard.spec.ts
├── a11y/                   # Accessibility tests
│   ├── navigation.spec.ts
│   └── forms.spec.ts
├── performance/            # Performance tests
│   └── critical-pages.spec.ts
└

Related in Design