react-testing
React Testing Library patterns for testing React components, hooks, and context. Use when testing React applications.
Install
mkdir -p .claude/skills/react-testing && curl -L -o skill.zip "https://mcp.directory/api/skills/download/4978" && unzip -o skill.zip -d .claude/skills/react-testing && rm skill.zipInstalls to .claude/skills/react-testing
About this skill
React Testing
For general UI testing patterns (queries, events, async, accessibility), load the front-end-testing skill. For TDD workflow, load the tdd skill.
Vitest Browser Mode with React (Preferred)
Always prefer vitest-browser-react over @testing-library/react. Tests run in a real browser, giving production-accurate rendering, events, and CSS.
Setup
npm install -D vitest @vitest/browser-playwright vitest-browser-react @vitejs/plugin-react
// vitest.config.ts
import { defineConfig } from 'vitest/config'
import { playwright } from '@vitest/browser-playwright'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
test: {
browser: {
enabled: true,
provider: playwright(),
headless: true,
instances: [{ browser: 'chromium' }],
},
},
})
Component Testing
import { render } from 'vitest-browser-react'
import { expect, test } from 'vitest'
test('should display user name when provided', async () => {
const screen = await render(<UserProfile name="Alice" email="[email protected]" />)
await expect.element(screen.getByText(/alice/i)).toBeVisible()
await expect.element(screen.getByText(/[email protected]/i)).toBeVisible()
})
Key differences from @testing-library/react:
render()is async — useawait- Returns a
screenscoped to the rendered component - Use
expect.element()for auto-retrying assertions - No
act()wrapper needed — CDP events + retry handle timing - Auto-cleanup happens before each test (not after), so components stay visible for debugging
Testing Props and Callbacks
test('should call onSubmit when form submitted', async () => {
const handleSubmit = vi.fn()
const screen = await render(<LoginForm onSubmit={handleSubmit} />)
await screen.getByLabelText(/email/i).fill('[email protected]')
await screen.getByRole('button', { name: /submit/i }).click()
expect(handleSubmit).toHaveBeenCalledWith({
email: '[email protected]',
})
})
Testing Conditional Rendering
test('should show error message when login fails', async () => {
server.use(
http.post('/api/login', () => {
return HttpResponse.json({ error: 'Invalid credentials' }, { status: 401 })
})
)
const screen = await render(<LoginForm />)
await screen.getByLabelText(/email/i).fill('[email protected]')
await screen.getByRole('button', { name: /submit/i }).click()
await expect.element(screen.getByText(/invalid credentials/i)).toBeVisible()
})
Testing Hooks with renderHook
import { renderHook } from 'vitest-browser-react'
test('should toggle value', async () => {
const { result } = await renderHook(() => useToggle(false))
expect(result.current.value).toBe(false)
await act(() => {
result.current.toggle()
})
expect(result.current.value).toBe(true)
})
Testing Context Providers
test('should show user menu when authenticated', async () => {
const screen = await render(
<AuthProvider initialUser={{ name: 'Alice', role: 'admin' }}>
<Dashboard />
</AuthProvider>
)
await expect.element(screen.getByRole('button', { name: /user menu/i })).toBeVisible()
})
For hooks that need context:
const { result } = await renderHook(() => useAuth(), {
wrapper: ({ children }) => (
<AuthProvider>{children}</AuthProvider>
),
})
Legacy: @testing-library/react Patterns
The patterns below apply when using @testing-library/react with jsdom. Prefer vitest-browser-react for new projects.
Testing React Components
React components are just functions that return JSX. Test them like functions: inputs (props) → output (rendered DOM).
Basic Component Testing
// ✅ CORRECT - Test component behavior
it('should display user name when provided', () => {
render(<UserProfile name="Alice" email="[email protected]" />);
expect(screen.getByText(/alice/i)).toBeInTheDocument();
expect(screen.getByText(/[email protected]/i)).toBeInTheDocument();
});
// ❌ WRONG - Testing implementation
it('should set name state', () => {
const wrapper = mount(<UserProfile name="Alice" />);
expect(wrapper.state('name')).toBe('Alice'); // Internal state!
});
Testing Props
// ✅ CORRECT - Test how props affect rendered output
it('should call onSubmit when form submitted', async () => {
const handleSubmit = vi.fn();
const user = userEvent.setup();
render(<LoginForm onSubmit={handleSubmit} />);
await user.type(screen.getByLabelText(/email/i), '[email protected]');
await user.click(screen.getByRole('button', { name: /submit/i }));
expect(handleSubmit).toHaveBeenCalledWith({
email: '[email protected]',
});
});
Testing Conditional Rendering
// ✅ CORRECT - Test what user sees in different states
it('should show error message when login fails', async () => {
server.use(
http.post('/api/login', () => {
return HttpResponse.json({ error: 'Invalid credentials' }, { status: 401 });
})
);
const user = userEvent.setup();
render(<LoginForm />);
await user.type(screen.getByLabelText(/email/i), '[email protected]');
await user.click(screen.getByRole('button', { name: /submit/i }));
await screen.findByText(/invalid credentials/i);
});
Testing React Hooks
Custom Hooks with renderHook
Built into @testing-library/react (import directly, no separate package needed):
import { renderHook } from '@testing-library/react';
it('should toggle value', () => {
const { result } = renderHook(() => useToggle(false));
expect(result.current.value).toBe(false);
act(() => {
result.current.toggle();
});
expect(result.current.value).toBe(true);
});
Pattern:
result.current- Current return value of hookact()- Wrap state updatesrerender()- Re-run hook with new props
Hooks with Props
it('should accept initial value', () => {
const { result, rerender } = renderHook(
({ initialValue }) => useCounter(initialValue),
{ initialProps: { initialValue: 10 } }
);
expect(result.current.count).toBe(10);
// Test with different initial value
rerender({ initialValue: 20 });
expect(result.current.count).toBe(20);
});
Testing Context
wrapper Option
For hooks that need context providers:
const { result } = renderHook(() => useAuth(), {
wrapper: ({ children }) => (
<AuthProvider>
{children}
</AuthProvider>
),
});
expect(result.current.user).toBeNull();
act(() => {
result.current.login({ email: '[email protected]' });
});
expect(result.current.user).toEqual({ email: '[email protected]' });
Multiple Providers
const AllProviders = ({ children }) => (
<AuthProvider>
<ThemeProvider>
<RouterProvider>
{children}
</RouterProvider>
</ThemeProvider>
</AuthProvider>
);
const { result } = renderHook(() => useMyHook(), {
wrapper: AllProviders,
});
Testing Components with Context
// ✅ CORRECT - Wrap component in provider
const renderWithAuth = (ui, { user = null, ...options } = {}) => {
return render(
<AuthProvider initialUser={user}>
{ui}
</AuthProvider>,
options
);
};
it('should show user menu when authenticated', () => {
renderWithAuth(<Dashboard />, {
user: { name: 'Alice', role: 'admin' },
});
expect(screen.getByRole('button', { name: /user menu/i })).toBeInTheDocument();
});
Testing Forms
Controlled Inputs
it('should update input value as user types', async () => {
const user = userEvent.setup();
render(<SearchInput />);
const input = screen.getByLabelText(/search/i);
await user.type(input, 'react');
expect(input).toHaveValue('react');
});
Form Submissions
it('should submit form with user input', async () => {
const handleSubmit = vi.fn();
const user = userEvent.setup();
render(<RegistrationForm onSubmit={handleSubmit} />);
await user.type(screen.getByLabelText(/name/i), 'Alice');
await user.type(screen.getByLabelText(/email/i), '[email protected]');
await user.type(screen.getByLabelText(/password/i), 'password123');
await user.click(screen.getByRole('button', { name: /sign up/i }));
expect(handleSubmit).toHaveBeenCalledWith({
name: 'Alice',
email: '[email protected]',
password: 'password123',
});
});
Form Validation
it('should show validation errors for invalid input', async () => {
const user = userEvent.setup();
render(<RegistrationForm />);
// Submit empty form
await user.click(screen.getByRole('button', { name: /sign up/i }));
// Validation errors appear
expect(screen.getByText(/name is required/i)).toBeInTheDocument();
expect(screen.getByText(/email is required/i)).toBeInTheDocument();
expect(screen.getByText(/password is required/i)).toBeInTheDocument();
});
React-Specific Anti-Patterns
1. Unnecessary act() wrapping
❌ WRONG - Manual act() everywhere
act(() => {
render(<MyComponent />);
});
await act(async () => {
await user.click(button);
});
✅ CORRECT - RTL handles it
render(<MyComponent />);
await user.click(button);
Modern RTL auto-wraps:
render()userEventmethodsfireEventwaitFor,findBy
When you DO need manual act():
- Custom hook state updates (
renderHook) - Direct state mutations (rare, usually bad practice)
2. Manual cleanup() calls
❌ WRONG - Manual cleanup
afterEach(() => {
cleanup(); // Automatic since RTL 9!
});
✅ CORRECT - No cleanup needed
// Cleanup happens automatically after each test
3. beforeEach render pattern
❌ WRONG - Shared render in beforeEach
let button;
beforeEach(() => {
render(<MyComponent />);
button = screen.getByRole('button'); // Shared state
---
*Content truncated.*
More by citypaul
View all skills by citypaul →You might also like
flutter-development
aj-geddes
Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.
ui-ux-pro-max
nextlevelbuilder
"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."
drawio-diagrams-enhanced
jgtolentino
Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.
godot
bfollington
This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.
nano-banana-pro
garg-aayush
Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.
pdf-to-markdown
aliceisjustplaying
Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.
Related MCP Servers
Browse all serversCreate modern React UI components instantly with Magic AI Agent. Integrates with top IDEs for fast, stunning design and
Access shadcn/ui v4 components, blocks, and demos for rapid React UI library development. Seamless integration and sourc
Explore Magic UI, a React UI library offering structured component access, code suggestions, and installation guides for
Explore MCP-UI Widgets, a React UI library offering timers, stopwatches, and unit converters for dynamic, customizable R
FlyonUI is a React UI library for accessing component code, block metadata, and building workflows with conversational c
AI-ready access to Grafana UI: full React component library—TypeScript source, MDX docs, Storybook examples, tests, and
Stay ahead of the MCP ecosystem
Get weekly updates on new skills and servers.