React Testing
Full Reference: See advanced.md for MSW setup, testing hooks, testing context, forms, accessibility testing, snapshots, and test patterns.
Deep Knowledge: Use mcp__documentation__fetch_docs with technology: react topic: testing for comprehensive documentation.
Setup with Vitest + Testing Library
// vitest.config.ts
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
globals: true,
setupFiles: './src/test/setup.ts',
css: true,
},
});
// src/test/setup.ts
import '@testing-library/jest-dom/vitest';
import { cleanup } from '@testing-library/react';
import { afterEach } from 'vitest';
afterEach(() => {
cleanup();
});
Basic Component Testing
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect, vi } from 'vitest';
describe('Button', () => {
it('renders children', () => {
render(<Button => {}}>Click me</Button>);
expect(screen.getByRole('button', { name: /click me/i })).toBeInTheDocument();
});
it('calls onClick when clicked', async () => {
const handleClick = vi.fn();
render(<Button me</Button>);
await userEvent.click(screen.getByRole('button'));
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('is disabled when disabled prop is true', () => {
render(<Button => {}} disabled>Click me</Button>);
expect(screen.getByRole('button')).toBeDisabled();
});
});
Query Methods
// Priority order (prefer accessible queries)
// 1. getByRole - accessible to everyone
screen.getByRole('button', { name: /submit/i });
screen.getByRole('textbox', { name: /email/i });
screen.getByRole('heading', { level: 1 });
// 2. getByLabelText - for form fields
screen.getByLabelText(/email address/i);
// 3. getByPlaceholderText
screen.getByPlaceholderText(/enter your email/i);
// 4. getByText - for non-interactive elements
screen.getByText(/welcome to our app/i);
// 5. getByDisplayValue - for input values
screen.getByDisplayValue(/john@example.com/i);
// 6. getByAltText - for images
screen.getByAltText(/user avatar/i);
// 7. getByTitle
screen.getByTitle(/close/i);
// 8. getByTestId - last resort
screen.getByTestId('custom-element');
// Query variants
screen.getByRole('button'); // Throws if not found
screen.queryByRole('button'); // Returns null if not found
screen.findByRole('button'); // Returns Promise, waits for element
screen.getAllByRole('button'); // Returns array, throws if none
screen.queryAllByRole('button'); // Returns array (possibly empty)
screen.findAllByRole('button'); // Returns Promise of array
User Events
import userEvent from '@testing-library/user-event';
describe('Form', () => {
it('submits with user input', async () => {
const user = userEvent.setup();
const handleSubmit = vi.fn();
render(<LoginForm />);
// Type in inputs
await user.type(screen.getByLabelText(/email/i), 'john@example.com');
await user.type(screen.getByLabelText(/password/i), 'secret123');
// Click submit
await user.click(screen.getByRole('button', { name: /sign in/i }));
expect(handleSubmit).toHaveBeenCalledWith({
email: 'john@example.com',
password: 'secret123',
});
});
it('handles keyboard navigation', async () => {
const user = userEvent.setup();
render(<Form />);
// Tab through inputs
await user.tab();
expect(screen.getByLabelText(/email/i)).toHaveFocus();
await user.tab();
expect(screen.getByLabelText(/password/i)).toHaveFocus();
// Type and submit with Enter
await user.type(screen.getByLabelText(/password/i), 'secret{Enter}');
});
it('handles select and checkbox', async () => {
const user = userEvent.setup();
render(<SettingsForm />);
// Select option
await user.selectOptions(screen.getByRole('combobox'), ['dark']);
// Toggle checkbox
await user.click(screen.getByRole('checkbox', { name: /notifications/i }));
expect(screen.getByRole('checkbox')).toBeChecked();
});
});
Async Testing
describe('UserProfile', () => {
it('shows loading then user data', async () => {
render(<UserProfile userId="123" />);
// Initially shows loading
expect(screen.getByText(/loading/i)).toBeInTheDocument();
// Wait for data to load
await waitFor(() => {
expect(screen.getByText('John Doe')).toBeInTheDocument();
});
// Loading is gone
expect(screen.queryByText(/loading/i)).not.toBeInTheDocument();
});
});
// Using findBy (combines getBy + waitFor)
it('loads and displays items', async () => {
render(<ItemList />);
// findBy waits for element
const items = await screen.findAllByRole('listitem');
expect(items).toHaveLength(3);
});
// waitForElementToBeRemoved
it('removes loading indicator', async () => {
render(<DataLoader />);
await waitForElementToBeRemoved(() => screen.queryByText(/loading/i));
expect(screen.getByText('Data loaded')).toBeInTheDocument();
});
Mocking
Mock Functions
import { vi } from 'vitest';
const mockFn = vi.fn();
mockFn.mockReturnValue('default');
mockFn.mockReturnValueOnce('first call');
mockFn.mockImplementation((x) => x * 2);
mockFn.mockResolvedValue({ data: [] });
mockFn.mockRejectedValue(new Error('Failed'));
// Assertions
expect(mockFn).toHaveBeenCalled();
expect(mockFn).toHaveBeenCalledTimes(2);
expect(mockFn).toHaveBeenCalledWith('arg1', 'arg2');
expect(mockFn).toHaveBeenLastCalledWith('last arg');
Mock Modules
// Mock a module
vi.mock('@/lib/api', () => ({
fetchUsers: vi.fn(() => Promise.resolve([{ id: 1, name: 'John' }])),
}));
// Import after mocking
import { fetchUsers } from '@/lib/api';
it('fetches users', async () => {
render(<UserList />);
expect(fetchUsers).toHaveBeenCalled();
await screen.findByText('John');
});
Common Pitfalls
| Issue |
Problem |
Solution |
| Test not finding element |
Element rendered async |
Use findBy or waitFor |
| State not updating |
Missing act() |
Use userEvent (handles act) |
| Tests affecting each other |
Shared state |
Clean up in afterEach |
| Flaky tests |
Race conditions |
Use proper async patterns |
Best Practices
- Test behavior, not implementation
- Use accessible queries (getByRole)
- Use userEvent over fireEvent
- Test error states
- Use MSW for API mocking
- Don't test implementation details
- Don't test third-party libraries
- Don't overuse snapshots
When NOT to Use This Skill
- End-to-end testing - Use Playwright skill for full E2E flows
- Backend testing - Use framework-specific testing skills
- Performance testing - Use specialized performance testing tools
- Visual regression testing - Use tools like Percy or Chromatic
Anti-Patterns
| Anti-Pattern |
Problem |
Solution |
| Testing implementation details |
Brittle tests |
Test user-facing behavior |
| Using getByTestId first |
Not testing accessibility |
Prefer getByRole, getByLabelText |
| Using fireEvent instead of userEvent |
Doesn't simulate real user interaction |
Use userEvent for realistic tests |
| Not waiting for async updates |
Flaky tests |
Use findBy or waitFor |
| Snapshot testing everything |
Hard to maintain |
Use sparingly for stable UI |
| Testing third-party libraries |
Wasted effort |
Trust library tests, test your integration |
| Not testing error states |
Missing edge cases |
Test loading, error, empty states |
| Shallow rendering |
Missing integration issues |
Use full render |
Quick Troubleshooting
| Issue |
Likely Cause |
Fix |
| Element not found |
Query timing, wrong query |
Use findBy for async or check query |
| Test timeout |
Async operation not completing |
Check waitFor timeout, fix async code |
| Act warning |
State update outside act |
Use userEvent or wrap in act() |
| Flaky tests |
Race conditions, timing |
Use proper async queries (findBy, waitFor) |
| Can't test hooks |
Testing implementation |
Extract to component or use renderHook |
| Mock not working |
Mock after import |
Mock before importing component |
| Tests affecting each other |
Shared state |
Clean up in afterEach |
Reference Documentation
1---2name: react-testing3description: |4 React component testing with Testing Library and Vitest. Covers unit tests,5 integration tests, async testing, mocking, user events, accessibility testing,6 and test patterns.78 USE WHEN: user mentions "React testing", "Testing Library", "Vitest", "component tests",9 "userEvent", "screen queries", "MSW", asks about "testing React components",10 "mocking in tests", "accessibility testing", "React test patterns"1112 DO NOT USE FOR: E2E testing - use Playwright skill instead,13 backend testing - use framework-specific testing skills,14 general testing concepts - use testing framework skills15allowed-tools: Read, Grep, Glob, Write, Edit16metadata:17 source: https://skillmd.com/skills/claude-dev-suite/react-testing18---1920# React Testing2122> **Full Reference**: See [advanced.md](advanced.md) for MSW setup, testing hooks, testing context, forms, accessibility testing, snapshots, and test patterns.2324> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `react` topic: `testing` for comprehensive documentation.2526## Setup with Vitest + Testing Library2728```ts29// vitest.config.ts30import { defineConfig } from 'vitest/config';31import react from '@vitejs/plugin-react';3233export default defineConfig({34 plugins: [react()],35 test: {36 environment: 'jsdom',37 globals: true,38 setupFiles: './src/test/setup.ts',39 css: true,40 },41});4243// src/test/setup.ts44import '@testing-library/jest-dom/vitest';45import { cleanup } from '@testing-library/react';46import { afterEach } from 'vitest';4748afterEach(() => {49 cleanup();50});51```5253---5455## Basic Component Testing5657```tsx58import { render, screen } from '@testing-library/react';59import userEvent from '@testing-library/user-event';60import { describe, it, expect, vi } from 'vitest';6162describe('Button', () => {63 it('renders children', () => {64 render(<Button onClick={() => {}}>Click me</Button>);65 expect(screen.getByRole('button', { name: /click me/i })).toBeInTheDocument();66 });6768 it('calls onClick when clicked', async () => {69 const handleClick = vi.fn();70 render(<Button onClick={handleClick}>Click me</Button>);7172 await userEvent.click(screen.getByRole('button'));7374 expect(handleClick).toHaveBeenCalledTimes(1);75 });7677 it('is disabled when disabled prop is true', () => {78 render(<Button onClick={() => {}} disabled>Click me</Button>);79 expect(screen.getByRole('button')).toBeDisabled();80 });81});82```8384---8586## Query Methods8788```tsx89// Priority order (prefer accessible queries)90// 1. getByRole - accessible to everyone91screen.getByRole('button', { name: /submit/i });92screen.getByRole('textbox', { name: /email/i });93screen.getByRole('heading', { level: 1 });9495// 2. getByLabelText - for form fields96screen.getByLabelText(/email address/i);9798// 3. getByPlaceholderText99screen.getByPlaceholderText(/enter your email/i);100101// 4. getByText - for non-interactive elements102screen.getByText(/welcome to our app/i);103104// 5. getByDisplayValue - for input values105screen.getByDisplayValue(/john@example.com/i);106107// 6. getByAltText - for images108screen.getByAltText(/user avatar/i);109110// 7. getByTitle111screen.getByTitle(/close/i);112113// 8. getByTestId - last resort114screen.getByTestId('custom-element');115116// Query variants117screen.getByRole('button'); // Throws if not found118screen.queryByRole('button'); // Returns null if not found119screen.findByRole('button'); // Returns Promise, waits for element120screen.getAllByRole('button'); // Returns array, throws if none121screen.queryAllByRole('button'); // Returns array (possibly empty)122screen.findAllByRole('button'); // Returns Promise of array123```124125---126127## User Events128129```tsx130import userEvent from '@testing-library/user-event';131132describe('Form', () => {133 it('submits with user input', async () => {134 const user = userEvent.setup();135 const handleSubmit = vi.fn();136137 render(<LoginForm onSubmit={handleSubmit} />);138139 // Type in inputs140 await user.type(screen.getByLabelText(/email/i), 'john@example.com');141 await user.type(screen.getByLabelText(/password/i), 'secret123');142143 // Click submit144 await user.click(screen.getByRole('button', { name: /sign in/i }));145146 expect(handleSubmit).toHaveBeenCalledWith({147 email: 'john@example.com',148 password: 'secret123',149 });150 });151152 it('handles keyboard navigation', async () => {153 const user = userEvent.setup();154 render(<Form />);155156 // Tab through inputs157 await user.tab();158 expect(screen.getByLabelText(/email/i)).toHaveFocus();159160 await user.tab();161 expect(screen.getByLabelText(/password/i)).toHaveFocus();162163 // Type and submit with Enter164 await user.type(screen.getByLabelText(/password/i), 'secret{Enter}');165 });166167 it('handles select and checkbox', async () => {168 const user = userEvent.setup();169 render(<SettingsForm />);170171 // Select option172 await user.selectOptions(screen.getByRole('combobox'), ['dark']);173174 // Toggle checkbox175 await user.click(screen.getByRole('checkbox', { name: /notifications/i }));176177 expect(screen.getByRole('checkbox')).toBeChecked();178 });179});180```181182---183184## Async Testing185186```tsx187describe('UserProfile', () => {188 it('shows loading then user data', async () => {189 render(<UserProfile userId="123" />);190191 // Initially shows loading192 expect(screen.getByText(/loading/i)).toBeInTheDocument();193194 // Wait for data to load195 await waitFor(() => {196 expect(screen.getByText('John Doe')).toBeInTheDocument();197 });198199 // Loading is gone200 expect(screen.queryByText(/loading/i)).not.toBeInTheDocument();201 });202});203204// Using findBy (combines getBy + waitFor)205it('loads and displays items', async () => {206 render(<ItemList />);207208 // findBy waits for element209 const items = await screen.findAllByRole('listitem');210 expect(items).toHaveLength(3);211});212213// waitForElementToBeRemoved214it('removes loading indicator', async () => {215 render(<DataLoader />);216217 await waitForElementToBeRemoved(() => screen.queryByText(/loading/i));218219 expect(screen.getByText('Data loaded')).toBeInTheDocument();220});221```222223---224225## Mocking226227### Mock Functions228229```tsx230import { vi } from 'vitest';231232const mockFn = vi.fn();233mockFn.mockReturnValue('default');234mockFn.mockReturnValueOnce('first call');235mockFn.mockImplementation((x) => x * 2);236mockFn.mockResolvedValue({ data: [] });237mockFn.mockRejectedValue(new Error('Failed'));238239// Assertions240expect(mockFn).toHaveBeenCalled();241expect(mockFn).toHaveBeenCalledTimes(2);242expect(mockFn).toHaveBeenCalledWith('arg1', 'arg2');243expect(mockFn).toHaveBeenLastCalledWith('last arg');244```245246### Mock Modules247248```tsx249// Mock a module250vi.mock('@/lib/api', () => ({251 fetchUsers: vi.fn(() => Promise.resolve([{ id: 1, name: 'John' }])),252}));253254// Import after mocking255import { fetchUsers } from '@/lib/api';256257it('fetches users', async () => {258 render(<UserList />);259260 expect(fetchUsers).toHaveBeenCalled();261 await screen.findByText('John');262});263```264265---266267## Common Pitfalls268269| Issue | Problem | Solution |270|-------|---------|----------|271| Test not finding element | Element rendered async | Use `findBy` or `waitFor` |272| State not updating | Missing `act()` | Use `userEvent` (handles act) |273| Tests affecting each other | Shared state | Clean up in `afterEach` |274| Flaky tests | Race conditions | Use proper async patterns |275276## Best Practices277278- Test behavior, not implementation279- Use accessible queries (getByRole)280- Use userEvent over fireEvent281- Test error states282- Use MSW for API mocking283- Don't test implementation details284- Don't test third-party libraries285- Don't overuse snapshots286287## When NOT to Use This Skill288289- **End-to-end testing** - Use Playwright skill for full E2E flows290- **Backend testing** - Use framework-specific testing skills291- **Performance testing** - Use specialized performance testing tools292- **Visual regression testing** - Use tools like Percy or Chromatic293294## Anti-Patterns295296| Anti-Pattern | Problem | Solution |297|--------------|---------|----------|298| Testing implementation details | Brittle tests | Test user-facing behavior |299| Using getByTestId first | Not testing accessibility | Prefer getByRole, getByLabelText |300| Using fireEvent instead of userEvent | Doesn't simulate real user interaction | Use userEvent for realistic tests |301| Not waiting for async updates | Flaky tests | Use findBy or waitFor |302| Snapshot testing everything | Hard to maintain | Use sparingly for stable UI |303| Testing third-party libraries | Wasted effort | Trust library tests, test your integration |304| Not testing error states | Missing edge cases | Test loading, error, empty states |305| Shallow rendering | Missing integration issues | Use full render |306307## Quick Troubleshooting308309| Issue | Likely Cause | Fix |310|-------|--------------|-----|311| Element not found | Query timing, wrong query | Use findBy for async or check query |312| Test timeout | Async operation not completing | Check waitFor timeout, fix async code |313| Act warning | State update outside act | Use userEvent or wrap in act() |314| Flaky tests | Race conditions, timing | Use proper async queries (findBy, waitFor) |315| Can't test hooks | Testing implementation | Extract to component or use renderHook |316| Mock not working | Mock after import | Mock before importing component |317| Tests affecting each other | Shared state | Clean up in afterEach |318319## Reference Documentation320321- [Testing Library](https://testing-library.com/docs/react-testing-library/intro/)322- [Vitest](https://vitest.dev/)323- [MSW](https://mswjs.io/)324- MCP: `mcp__documentation__fetch_docs` → technology: `react`, topic: `testing`