Frontend Testing
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.
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
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.