react-testing
React component testing with React Testing Library, Vitest/Jest, MSW for network mocking, accessibility assertions with axe, and the decision boundary between component tests and Playwright/Cypress end-to-end runs. Use when writing or fixing tests for React components, hooks, or pages.
By affaan-m · 2,905 installs
npx skills add affaan-m/ecc --skill react-testing
Source repository · Upstream listing
React Testing
Comprehensive React testing patterns for behavior focused component tests, custom hook tests, accessibility assertions, and network level mocking.
When to Activate
Writing tests for React components, custom hooks, or pages
Adding test coverage to legacy untested components
Migrating from Enzyme or class component era patterns to React Testing Library
Setting up Vitest or Jest for a new React project
Mocking HTTP requests in tests
Asserting accessibility violations
Deciding which tests belong in RTL vs Playwright Component Testing vs full E2E
Core Principle
Test what the user sees and does, not implementation details.
A test should:
Render the component with the same providers it has in production
Interact with it via accessible queries (role, label) and userEvent
Assert visible output and observable side effects (callback fired, request sent)
A test should NOT:
Inspect component state, props passed to children, or which hooks were called
Mock React itself or framework hooks
Assert on the number of renders or DOM structure beyond what affects users
Library Choice
Runner When Note
Vitest Vite, Remix, modern setups Faster, native ESM, Jest compatible API
Jest Next.js, CRA, established repos Default for many React projects
Playwright Component Testing Real browser engine needed Use when JSDOM lacks the required feature
Cypress Component Testing Real browser, Cypress already in use Alternative to Playwright CT
Pick one. Do not run RTL + Vitest AND Playwright CT in the same repo unless you have a clear lane separation.
Query Priority
React Testing Library exposes queries in three tiers — use top down:
1. Accessible to everyone : getByRole , getByLabelText , getByPlaceholderText , getByText , getByDisplayValue
2. Semantic : getByAltText , getByTitle
3. Test IDs (escape hatch) : getByTestId
Variants:
getBy — throws if no match
queryBy — returns null (use for "assert absence")
findBy — async, returns a Promise (use for elements that appear after async work)
User Interaction with userEvent
Always await userEvent calls
Call userEvent.setup() once per test, reuse the returned user
userEvent simulates a real browser sequence; fireEvent dispatches a single synthetic event — prefer userEvent
Async Patterns
Never setTimeout + assertion — flaky. Use the matchers above.
Network Mocking with MSW
Mock Service Worker mocks at the network layer. The component, hooks, and fetch library all behave exactly as in production.
Setup
Configure onUnhandledRequest: "error" so any unmocked request fails the test loudly — silent passes are worse than red.
Per test override
Provider Wrapping
Wrap providers once in a test utils.tsx :
Then import { renderWithProviders, screen } from "test utils" in every test file.
Custom Hook Testing
Wrap state changing calls in act
Test through the hook's public API only
For hooks that use context, pass a wrapper
Accessibility Assertions
Run axe in component tests for every interactive component. Catches:
Missing labels on form inputs
Invalid ARIA usage
Poor color contrast (limited — JSDOM has no real CSS engine, so this works for inline styles only; visual contrast belongs in Playwright)
Missing alt text on images
Heading order violations
Cross link: [skills/accessibility/SKILL.md](../accessibility/SKILL.md) for the broader a11y testing playbook.
When NOT to Use Snapshot Tests
Snapshots of rendered output:
Break on every styling change
Get rubber stamped during review
Test implementation detail (DOM structure), not behavior
Acceptable snapshot uses:
Pure data serialization functions ( formatInvoice(invoice) stable string)
Generated config files (e.g., webpack config output)
For visual regression on components, use Playwright/Cypress screenshots or Percy/Chromatic — actual visual diffs, not DOM strings.
When to Reach for Playwright / Cypress
JSDOM (used by Vitest/Jest) cannot:
Render real layout (flexbox, grid, viewport queries)
Run native browser animation, CSS transitions
Test scrolling behavior, drag and drop, paste from clipboard
Handle iframes, popups, downloads, cross origin flows
Run real network in a controlled environment with full DevTools support
For any of those, use Playwright Component Testing (component test in real browser) or full E2E. See [e2e testing skill](../e2e testing/SKILL.md).
Decision boundary:
A hook, a presentational component, a form with logic RTL
A component whose layout matters or that uses browser APIs not in JSDOM Playwright CT
A full user flow across multiple pages Playwright/Cypress E2E
Coverage Targets
Layer Target
Pure utilities =90%
Custom hooks =85%
Presentational components =80% — behavior, not lines
Container components =70% — golden paths + error states
Pages E2E covered separately; smoke test minimum
Configure via vitest.config.ts / jest.config.js :
Anti Patterns
container.querySelector("...") — bypasses accessibility queries, lets tests pass when real users would fail
Asserting on number of renders — implementation detail
jest.mock("react", ...) — never mock React. Refactor the component instead
Mocking child components by default — tests the integration, not isolation. Mock only when the child has heavy side effects
Ignoring act() warnings — they signal real bugs (state update after unmount, missing async wrapping)
Sharing mutable state across tests — flakes when test order changes
Tests that pass with it.skip() removed — your test does not actually assert what you think
TDD Workflow
For new components:
1. Define the component's prop type and signature
2. Write the first test for the simplest case
3. Verify it fails for the right reason
4. Implement just enough to pass
5. Add the next test case
6. Refactor when the third similar test reveals a pattern
Test Commands
Related
Rules: [rules/react/testing.md](../../rules/react/testing.md)
Skills: [react patterns](../react patterns/SKILL.md), [accessibility](../accessibility/SKILL.md), [e2e testing](../e2e testing/SKILL.md), [tdd workflow](../tdd workflow/SKILL.md)
Agents: react reviewer (reviews test quality during code review), tdd guide (enforces TDD process)
Commands: /react test , /react review
Examples
Form submission with MSW and userEvent
Testing an error boundary
Testing a Suspense boundary