{"slug":"react-testing","title":"react-testing","summary":"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 ","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-12-02T16:53:47.565494Z","repo":{"url":"https://github.com/beginwithu/agent-skills","stars":11,"forks":2,"license":"MIT","updatedAt":"2026-12-02T16:37:11Z"},"bodyHtml":"<hr>\n<h2>name: react-testing\ndescription: 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.\nmetadata:\norigin: ECC</h2>\n<h1>React Testing</h1>\n<p>Comprehensive React testing patterns for behavior-focused component tests, custom hook tests, accessibility assertions, and network-level mocking.</p>\n<h2>When to Activate</h2>\n<ul>\n<li>Writing tests for React components, custom hooks, or pages</li>\n<li>Adding test coverage to legacy untested components</li>\n<li>Migrating from Enzyme or class-component-era patterns to React Testing Library</li>\n<li>Setting up Vitest or Jest for a new React project</li>\n<li>Mocking HTTP requests in tests</li>\n<li>Asserting accessibility violations</li>\n<li>Deciding which tests belong in RTL vs Playwright Component Testing vs full E2E</li>\n</ul>\n<h2>Core Principle</h2>\n<p>Test what the user sees and does, not implementation details.</p>\n<p>A test should:</p>\n<ul>\n<li>Render the component with the same providers it has in production</li>\n<li>Interact with it via accessible queries (role, label) and <code>userEvent</code></li>\n<li>Assert visible output and observable side effects (callback fired, request sent)</li>\n</ul>\n<p>A test should NOT:</p>\n<ul>\n<li>Inspect component state, props passed to children, or which hooks were called</li>\n<li>Mock React itself or framework hooks</li>\n<li>Assert on the number of renders or DOM structure beyond what affects users</li>\n</ul>\n<h2>Library Choice</h2>\n<table>\n<thead>\n<tr>\n<th>Runner</th>\n<th>When</th>\n<th>Note</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><strong>Vitest</strong></td>\n<td>Vite, Remix, modern setups</td>\n<td>Faster, native ESM, Jest-compatible API</td>\n</tr>\n<tr>\n<td><strong>Jest</strong></td>\n<td>Next.js, CRA, established repos</td>\n<td>Default for many React projects</td>\n</tr>\n<tr>\n<td><strong>Playwright Component Testing</strong></td>\n<td>Real browser engine needed</td>\n<td>Use when JSDOM lacks the required feature</td>\n</tr>\n<tr>\n<td><strong>Cypress Component Testing</strong></td>\n<td>Real browser, Cypress already in use</td>\n<td>Alternative to Playwright CT</td>\n</tr>\n</tbody>\n</table>\n<p>Pick one. Do not run RTL + Vitest AND Playwright CT in the same repo unless you have a clear lane separation.</p>\n<h2>Query Priority</h2>\n<p>React Testing Library exposes queries in three tiers — use top-down:</p>\n<ol>\n<li><strong>Accessible to everyone</strong>: <code>getByRole</code>, <code>getByLabelText</code>, <code>getByPlaceholderText</code>, <code>getByText</code>, <code>getByDisplayValue</code></li>\n<li><strong>Semantic</strong>: <code>getByAltText</code>, <code>getByTitle</code></li>\n<li><strong>Test IDs (escape hatch)</strong>: <code>getByTestId</code></li>\n</ol>\n<pre><code>// Best\nscreen.getByRole(\"button\", { name: /save/i });\n\n// OK for inputs\nscreen.getByLabelText(\"Email\");\n\n// Last resort\nscreen.getByTestId(\"save-btn\");\n</code></pre>\n<p>Variants:</p>\n<ul>\n<li><code>getBy*</code> — throws if no match</li>\n<li><code>queryBy*</code> — returns <code>null</code> (use for \"assert absence\")</li>\n<li><code>findBy*</code> — async, returns a Promise (use for elements that appear after async work)</li>\n</ul>\n<h2>User Interaction with <code>userEvent</code></h2>\n<pre><code>import userEvent from \"@testing-library/user-event\";\n\ntest(\"submits the form\", async () =&gt; {\n  const user = userEvent.setup();\n  const onSubmit = vi.fn();\n  render(&lt;UserForm onSubmit={onSubmit} /&gt;);\n\n  await user.type(screen.getByLabelText(\"Email\"), \"user@example.com\");\n  await user.click(screen.getByRole(\"button\", { name: /save/i }));\n\n  expect(onSubmit).toHaveBeenCalledWith({ email: \"user@example.com\" });\n});\n</code></pre>\n<ul>\n<li>Always <code>await</code> userEvent calls</li>\n<li>Call <code>userEvent.setup()</code> once per test, reuse the returned <code>user</code></li>\n<li><code>userEvent</code> simulates a real browser sequence; <code>fireEvent</code> dispatches a single synthetic event — prefer <code>userEvent</code></li>\n</ul>\n<h2>Async Patterns</h2>\n<pre><code>// Element that appears after async work\nexpect(await screen.findByText(\"Loaded\")).toBeInTheDocument();\n\n// Side effect assertion\nawait waitFor(() =&gt; expect(saveSpy).toHaveBeenCalled());\n\n// Element that should disappear\nawait waitForElementToBeRemoved(() =&gt; screen.queryByText(\"Loading\"));\n</code></pre>\n<p>Never <code>setTimeout</code> + assertion — flaky. Use the matchers above.</p>\n<h2>Network Mocking with MSW</h2>\n<p>Mock Service Worker mocks at the network layer. The component, hooks, and fetch library all behave exactly as in production.</p>\n<h3>Setup</h3>\n<pre><code>// test/setup.ts\nimport { setupServer } from \"msw/node\";\nimport { http, HttpResponse } from \"msw\";\n\nexport const handlers = [\n  http.get(\"/api/users/:id\", ({ params }) =&gt;\n    HttpResponse.json({ id: params.id, name: \"Alice\" }),\n  ),\n  http.post(\"/api/users\", async ({ request }) =&gt; {\n    const body = await request.json();\n    return HttpResponse.json({ id: \"new-id\", ...body }, { status: 201 });\n  }),\n];\n\nexport const server = setupServer(...handlers);\n\nbeforeAll(() =&gt; server.listen({ onUnhandledRequest: \"error\" }));\nafterEach(() =&gt; server.resetHandlers());\nafterAll(() =&gt; server.close());\n</code></pre>\n<p>Configure <code>onUnhandledRequest: \"error\"</code> so any unmocked request fails the test loudly — silent passes are worse than red.</p>\n<h3>Per-test override</h3>\n<pre><code>test(\"renders error on 500\", async () =&gt; {\n  server.use(\n    http.get(\"/api/users/:id\", () =&gt; new HttpResponse(null, { status: 500 })),\n  );\n  render(&lt;UserPage id=\"1\" /&gt;);\n  expect(await screen.findByText(/something went wrong/i)).toBeInTheDocument();\n});\n</code></pre>\n<h2>Provider Wrapping</h2>\n<p>Wrap providers once in a <code>test-utils.tsx</code>:</p>\n<pre><code>// test-utils.tsx\nimport { render, RenderOptions } from \"@testing-library/react\";\nimport { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\n\nexport function renderWithProviders(\n  ui: React.ReactElement,\n  options?: RenderOptions,\n) {\n  const queryClient = new QueryClient({\n    defaultOptions: { queries: { retry: false } },\n  });\n\n  return render(\n    &lt;QueryClientProvider client={queryClient}&gt;\n      &lt;ThemeProvider theme={lightTheme}&gt;\n        &lt;MemoryRouter&gt;{ui}&lt;/MemoryRouter&gt;\n      &lt;/ThemeProvider&gt;\n    &lt;/QueryClientProvider&gt;,\n    options,\n  );\n}\n\nexport * from \"@testing-library/react\";\n</code></pre>\n<p>Then <code>import { renderWithProviders, screen } from \"test-utils\"</code> in every test file.</p>\n<h2>Custom Hook Testing</h2>\n<pre><code>import { renderHook, act } from \"@testing-library/react\";\n\ntest(\"useCounter increments and decrements\", () =&gt; {\n  const { result } = renderHook(() =&gt; useCounter(0));\n\n  expect(result.current.count).toBe(0);\n\n  act(() =&gt; result.current.increment());\n  expect(result.current.count).toBe(1);\n\n  act(() =&gt; result.current.decrement());\n  expect(result.current.count).toBe(0);\n});\n\ntest(\"useCounter accepts initial value\", () =&gt; {\n  const { result } = renderHook(() =&gt; useCounter(10));\n  expect(result.current.count).toBe(10);\n});\n\ntest(\"useUser fetches user data\", async () =&gt; {\n  // Instantiate QueryClient ONCE per test outside the wrapper so it survives re-renders.\n  // Creating it inside the wrapper closure resets cache state on every render, producing flaky tests.\n  const queryClient = new QueryClient({\n    defaultOptions: { queries: { retry: false } },\n  });\n  const wrapper = ({ children }: { children: React.ReactNode }) =&gt; (\n    &lt;QueryClientProvider client={queryClient}&gt;{children}&lt;/QueryClientProvider&gt;\n  );\n\n  const { result } = renderHook(() =&gt; useUser(\"1\"), { wrapper });\n\n  await waitFor(() =&gt; expect(result.current.isSuccess).toBe(true));\n  expect(result.current.data).toEqual({ id: \"1\", name: \"Alice\" });\n});\n</code></pre>\n<ul>\n<li>Wrap state-changing calls in <code>act</code></li>\n<li>Test through the hook's public API only</li>\n<li>For hooks that use context, pass a <code>wrapper</code></li>\n</ul>\n<h2>Accessibility Assertions</h2>\n<pre><code>import { axe, toHaveNoViolations } from \"jest-axe\"; // or vitest-axe\nexpect.extend(toHaveNoViolations);\n\ntest(\"UserCard has no a11y violations\", async () =&gt; {\n  const { container } = render(&lt;UserCard user={mockUser} /&gt;);\n  expect(await axe(container)).toHaveNoViolations();\n});\n</code></pre>\n<p>Run axe in component tests for every interactive component. Catches:</p>\n<ul>\n<li>Missing labels on form inputs</li>\n<li>Invalid ARIA usage</li>\n<li>Poor color contrast (limited — JSDOM has no real CSS engine, so this works for inline styles only; visual contrast belongs in Playwright)</li>\n<li>Missing alt text on images</li>\n<li>Heading order violations</li>\n</ul>\n<p>Cross-link: <a href=\"../accessibility/SKILL.md\">skills/accessibility/SKILL.md</a> for the broader a11y testing playbook.</p>\n<h2>When NOT to Use Snapshot Tests</h2>\n<p>Snapshots of rendered output:</p>\n<ul>\n<li>Break on every styling change</li>\n<li>Get rubber-stamped during review</li>\n<li>Test implementation detail (DOM structure), not behavior</li>\n</ul>\n<p>Acceptable snapshot uses:</p>\n<ul>\n<li>Pure data serialization functions (<code>formatInvoice(invoice)</code> -&gt; stable string)</li>\n<li>Generated config files (e.g., webpack config output)</li>\n</ul>\n<p>For visual regression on components, use Playwright/Cypress screenshots or Percy/Chromatic — actual visual diffs, not DOM strings.</p>\n<h2>When to Reach for Playwright / Cypress</h2>\n<p>JSDOM (used by Vitest/Jest) cannot:</p>\n<ul>\n<li>Render real layout (flexbox, grid, viewport queries)</li>\n<li>Run native browser animation, CSS transitions</li>\n<li>Test scrolling behavior, drag-and-drop, paste from clipboard</li>\n<li>Handle iframes, popups, downloads, cross-origin flows</li>\n<li>Run real network in a controlled environment with full DevTools support</li>\n</ul>\n<p>For any of those, use Playwright Component Testing (component test in real browser) or full E2E. See <a href=\"../e2e-testing/SKILL.md\">e2e-testing skill</a>.</p>\n<p>Decision boundary:</p>\n<ul>\n<li>A hook, a presentational component, a form with logic -&gt; RTL</li>\n<li>A component whose layout matters or that uses browser APIs not in JSDOM -&gt; Playwright CT</li>\n<li>A full user flow across multiple pages -&gt; Playwright/Cypress E2E</li>\n</ul>\n<h2>Coverage Targets</h2>\n<table>\n<thead>\n<tr>\n<th>Layer</th>\n<th>Target</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Pure utilities</td>\n<td>&gt;=90%</td>\n</tr>\n<tr>\n<td>Custom hooks</td>\n<td>&gt;=85%</td>\n</tr>\n<tr>\n<td>Presentational components</td>\n<td>&gt;=80% — behavior, not lines</td>\n</tr>\n<tr>\n<td>Container components</td>\n<td>&gt;=70% — golden paths + error states</td>\n</tr>\n<tr>\n<td>Pages</td>\n<td>E2E covered separately; smoke test minimum</td>\n</tr>\n</tbody>\n</table>\n<p>Configure via <code>vitest.config.ts</code> / <code>jest.config.js</code>:</p>\n<pre><code>// vitest.config.ts\ntest: {\n  coverage: {\n    provider: \"v8\",\n    reporter: [\"text\", \"html\", \"lcov\"],\n    thresholds: {\n      lines: 80,\n      functions: 80,\n      branches: 70,\n      statements: 80,\n    },\n  },\n}\n</code></pre>\n<h2>Anti-Patterns</h2>\n<ul>\n<li><code>container.querySelector(\"...\")</code> — bypasses accessibility queries, lets tests pass when real users would fail</li>\n<li>Asserting on number of renders — implementation detail</li>\n<li><code>jest.mock(\"react\", ...)</code> — never mock React. Refactor the component instead</li>\n<li>Mocking child components by default — tests the integration, not isolation. Mock only when the child has heavy side effects</li>\n<li>Ignoring <code>act()</code> warnings — they signal real bugs (state update after unmount, missing async wrapping)</li>\n<li>Sharing mutable state across tests — flakes when test order changes</li>\n<li>Tests that pass with <code>it.skip()</code> removed — your test does not actually assert what you think</li>\n</ul>\n<h2>TDD Workflow</h2>\n<pre><code>RED     -&gt; Write failing test for the next requirement\nGREEN   -&gt; Write minimal component code to pass\nREFACTOR -&gt; Improve the component, tests stay green\nREPEAT  -&gt; Next requirement\n</code></pre>\n<p>For new components:</p>\n<ol>\n<li>Define the component's prop type and signature</li>\n<li>Write the first test for the simplest case</li>\n<li>Verify it fails for the right reason</li>\n<li>Implement just enough to pass</li>\n<li>Add the next test case</li>\n<li>Refactor when the third similar test reveals a pattern</li>\n</ol>\n<h2>Test Commands</h2>\n<pre><code># Vitest\nvitest                            # watch\nvitest run                        # one-shot\nvitest run --coverage             # with coverage\nvitest run path/to/file.test.tsx  # single file\n\n# Jest\njest --watch\njest --coverage\njest path/to/file.test.tsx\n\n# CI mode\nCI=true vitest run --coverage\n</code></pre>\n<h2>Related</h2>\n<ul>\n<li>Rules: <a href=\"../../rules/react/testing.md\">rules/react/testing.md</a></li>\n<li>Skills: <a href=\"../react-patterns/SKILL.md\">react-patterns</a>, <a href=\"../accessibility/SKILL.md\">accessibility</a>, <a href=\"../e2e-testing/SKILL.md\">e2e-testing</a>, <a href=\"../tdd-workflow/SKILL.md\">tdd-workflow</a></li>\n<li>Agents: <code>react-reviewer</code> (reviews test quality during code review), <code>tdd-guide</code> (enforces TDD process)</li>\n<li>Commands: <code>/react-test</code>, <code>/react-review</code></li>\n</ul>\n<h2>Examples</h2>\n<h3>Form submission with MSW and userEvent</h3>\n<pre><code>test(\"submits user form and shows success\", async () =&gt; {\n  server.use(\n    http.post(\"/api/users\", () =&gt;\n      HttpResponse.json({ id: \"1\", name: \"Alice\" }, { status: 201 }),\n    ),\n  );\n\n  const user = userEvent.setup();\n  renderWithProviders(&lt;UserForm /&gt;);\n\n  await user.type(screen.getByLabelText(\"Name\"), \"Alice\");\n  await user.type(screen.getByLabelText(\"Email\"), \"alice@example.com\");\n  await user.click(screen.getByRole(\"button\", { name: /save/i }));\n\n  expect(await screen.findByText(/saved successfully/i)).toBeInTheDocument();\n});\n</code></pre>\n<h3>Testing an error boundary</h3>\n<pre><code>function Broken() {\n  throw new Error(\"boom\");\n}\n\ntest(\"error boundary renders fallback\", () =&gt; {\n  // Suppress React's console.error noise for the expected throw, then restore so\n  // the spy does not leak across tests and hide real errors elsewhere.\n  const errorSpy = vi.spyOn(console, \"error\").mockImplementation(() =&gt; {});\n  try {\n    render(\n      &lt;ErrorBoundary fallback={&lt;div&gt;Something went wrong&lt;/div&gt;}&gt;\n        &lt;Broken /&gt;\n      &lt;/ErrorBoundary&gt;,\n    );\n\n    expect(screen.getByText(\"Something went wrong\")).toBeInTheDocument();\n  } finally {\n    errorSpy.mockRestore();\n  }\n});\n</code></pre>\n<h3>Testing a Suspense boundary</h3>\n<pre><code>test(\"shows loading then content\", async () =&gt; {\n  renderWithProviders(\n    &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;\n      &lt;UserDetail id=\"1\" /&gt;\n    &lt;/Suspense&gt;,\n  );\n\n  expect(screen.getByText(\"Loading...\")).toBeInTheDocument();\n  expect(await screen.findByText(\"Alice\")).toBeInTheDocument();\n});\n</code></pre>\n","files":[{"path":"LICENSE","sizeBytes":1071,"isText":false},{"path":"SKILL.md","sizeBytes":13168,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-12-02T16:57:59.010608Z","sha256":"3A23036603F2CDE2DDB722CFFF8C7BBE8BC1F590CE3A23B825178CD978DE19AA","sizeBytes":6062},"review":null,"source":{"repositoryUrl":"https://github.com/beginwithu/agent-skills","path":"skills/react-testing","license":"MIT","commit":"a960304c52212f2e845067047f5cefc0c594d787","subtreeSha":"5F2572345067B19B0D1D1F22C8B29F49DC61DB5FC7FE824E83BCD672D3F4B3F6","lastSyncedAt":"2026-12-02T16:52:59.20206Z"},"reviewedAt":"2026-12-02T17:06:15.095752Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/beginwithu/agent-skills/tree/main/skills/react-testing"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install beginwithu-agent-skills@llmmart"},{"target":"git","command":"git clone https://github.com/beginwithu/agent-skills.git"}]}