/engineering-paved-path:react-testing-libraryfrom Engineering Paved Path
General-purpose React Testing Library guide with Vitest. Use when writing, reviewing, or setting up React component and hook tests. Covers project setup from scratch, RTL query priority, userEvent, async patterns, mocking strategies, and common anti-patterns. Applicable to any Vite + React project.
Ships in Engineering Paved Path. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
General-purpose guide for testing React components and hooks with React Testing Library (RTL) and Vitest. Project-agnostic — works with any Vite + React setup.
Load these with the Read tool only when the task calls for them:
| File | Read it when |
|---|---|
${CLAUDE_SKILL_DIR}/references/setup.md | The project has no RTL/Vitest setup yet — install, config, setup file, scripts |
${CLAUDE_SKILL_DIR}/references/spec-templates.md | You want a full worked test file — list-component and form specs end to end |
${CLAUDE_SKILL_DIR}/references/patterns.md | Render helpers, within scoping, renderHook, React Router wrapping |
${CLAUDE_SKILL_DIR}/references/mocking.md | Setting up MSW, vi.mock, context providers, or fake timers |
${CLAUDE_SKILL_DIR}/references/matchers.md | Looking up a jest-dom matcher |
"Write tests. Not too many. Mostly integration." — Kent C. Dodds
E2E ← Few: critical user journeys only (Playwright/Cypress)
Integration ← MOST tests: components with real providers, MSW for APIs
Unit ← Some: complex pure logic, utilities, formatters
Static Analysis ← Always: TypeScript, ESLint
Before writing tests, identify the component type and pick scenarios from this matrix. Write 1-3 tests per component — each test covers a full user flow, not a single assertion.
| # | Test | What it covers |
|---|---|---|
| 1 | Happy path: fill all fields → submit → success feedback | Rendering, typing, validation passing, API call, success state |
| 2 | Validation: submit empty/invalid → error messages appear | Required fields, validation rules, error rendering |
| 3 | API failure: fill valid → submit → server error shown | Error handling, error UI, form stays filled |
| # | Test | What it covers |
|---|---|---|
| 1 | Happy path: data loads → items render → user interacts | Loading state, data rendering, click/navigation |
| 2 | Empty state: no data → empty message shown | Zero-data handling |
| 3 | Error state: API fails → error message shown | Network failure handling |
| # | Test | What it covers |
|---|---|---|
| 1 | Happy path: data loads → full content renders → user actions work | Data fetching, rendering, interactions (edit/delete/comment) |
| 2 | Not found / error: invalid ID → appropriate message | 404 handling, error boundaries |
| # | Test | What it covers |
|---|---|---|
| 1 | Authenticated: user sees protected content and can interact | Auth context, content rendering, user actions |
| 2 | Unauthenticated: redirects or shows login prompt | Guard behavior, redirect |
| # | Test | What it covers |
|---|---|---|
| 1 | Renders with props and handles user interaction | Props → UI mapping, click/hover callbacks |
| 2 | Conditional rendering: different props → different output | Only if the component has meaningful branching |
For a full worked example of these scenarios in one file, read ${CLAUDE_SKILL_DIR}/references/spec-templates.md.
// Test runner — ALWAYS from vitest
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// RTL — render, screen, waitFor
import { render, screen, waitFor, within } from '@testing-library/react';
// User interaction — ALWAYS userEvent, NEVER fireEvent
import userEvent from '@testing-library/user-event';
// Hook testing
import { renderHook, act } from '@testing-library/react';
NEVER import from jest. Use vi.fn(), vi.spyOn(), vi.mock().
Queries are ordered by how closely they reflect user experience.
| Query | Use For |
|---|---|
getByRole | Buttons, links, headings, inputs, checkboxes, comboboxes — always try first |
getByLabelText | Form fields with a <label> |
getByPlaceholderText | Inputs without a label (prefer adding a label instead) |
getByText | Static text content — paragraphs, spans, error messages |
getByDisplayValue | Input with a current value |
| Query | Use For |
|---|---|
getByAltText | Images |
getByTitle | Elements with title attribute |
| Query | Use For |
|---|---|
getByTestId | Only when no accessible query works; requires data-testid |
| Variant | Returns | Use When |
|---|---|---|
getBy | Element or throws | Element must be present |
queryBy | Element or null | Asserting element does not exist |
findBy | Promise<Element> | Element appears after an async operation |
*AllBy | Array variants | Multiple matching elements |
getByRole('button', { name: /submit/i })
getByRole('heading', { level: 2 })
getByRole('textbox', { name: /email/i })
getByRole('link', { name: /read more/i })
getByRole('checkbox', { name: /agree/i })
getByRole('combobox') // <select>
getByRole('status') // role="status"
getByRole('alert') // role="alert"
getByRole('dialog') // <dialog> or role="dialog"
getByRole('navigation') // <nav>
Always call userEvent.setup() before rendering. All methods are async.
| Method | Purpose |
|---|---|
user.click(el) | Click |
user.dblClick(el) | Double-click |
user.type(el, 'text') | Type text (appends to existing value) |
user.clear(el) | Clear input value |
user.selectOptions(el, 'value') | Select dropdown option |
user.tab() | Tab to next focusable element |
user.keyboard('{Enter}') | Press a key |
user.hover(el) / user.unhover(el) | Mouse hover |
user.upload(el, file) | File upload |
Pattern:
const user = userEvent.setup();
render(<Component />);
await user.click(screen.getByRole('button', { name: /save/i }));
findBy — element appears after async workrender(<BlogList />);
expect(await screen.findByText('Blog Title')).toBeInTheDocument();
waitFor — multiple assertions, complex conditionsawait waitFor(() => {
expect(screen.getAllByRole('listitem')).toHaveLength(3);
});
waitForElementToBeRemoved — element disappearsrender(<BlogList />);
await waitForElementToBeRemoved(() => screen.queryByText('Loading...'));
setTimeout or fixed delaysact() directly unless testing hooks outside components — RTL wraps itfindBy is preferred over waitFor + getBy for single-element waitswaitFor retries until the callback passes or times out (default 1000ms)Mock the network, never the subject. MSW is the default for any data-fetching component because it intercepts at the network layer and keeps tests decoupled from the HTTP client; vi.mock at the API/hook level is the fallback when MSW is overkill. Never mock your own components, hooks, or context internals — render with the real provider.
Full setup for MSW, vi.mock, context providers, and fake timers: ${CLAUDE_SKILL_DIR}/references/mocking.md.
Test (as user-visible flows):
Skip:
useState values)BlogCard.jsx -> BlogCard.test.jsx.test.jsx extension (not .spec.jsx)describe per component/hook"user fills form and sees success message"vi.fn() for all mock functionsuserEvent.setup() before render()screen — never destructure from render()| Anti-Pattern | Fix |
|---|---|
| Many tiny tests with one assertion each | Combine into fewer flow tests that walk through a user journey |
fireEvent.click() | Use await user.click() from userEvent.setup() |
Destructuring from render() | Use screen.getByRole(...) |
getByTestId as first choice | Try getByRole, getByLabelText, getByText first |
Testing useState / hook internals | Test the rendered output instead |
setTimeout / fixed delays | Use findBy or waitFor |
| Snapshot tests replacing behavior tests | Write explicit assertions |
container.querySelector() | Use RTL queries |
| Shared mutable state between tests | Reset in beforeEach |
Importing from jest | Import from vitest (vi.fn(), vi.mock()) |
| Mocking what you're testing | Mock dependencies, not the subject |
act() wrapping RTL calls | RTL handles act() internally |
| Mocking Axios/fetch directly | Use MSW for network-level mocking |
| Testing every prop combination | Test the meaningful user-facing differences only |
What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
8 skills in this plugin
/fastify-best-practicesGuides development of Fastify Node.js backend servers and REST APIs using TypeScript or JavaScript. Use when building, configuring, or debugging a Fastify application — including defining routes, implementing plugins, setting up JSON Schema validation, handling errors, optimising performance, managing authentication, configuring CORS and security headers, integrating databases, working with WebSockets, and deploying to production. Covers the full Fastify request lifecycle (hooks, serialization, logging with Pino) and TypeScript integration via strip types. Trigger terms: Fastify, Node.js server, REST API, API routes, backend framework, fastify.config, server.ts, app.ts./next-best-practicesNext.js best practices - file conventions, RSC boundaries, data patterns, async APIs, metadata, error handling, route handlers, image/font optimization, bundling/onion-architectureEnforces Onion Architecture (dependencies point inward) on a TypeScript backend (a Fastify + Drizzle + Zod server/ package and a pure domain core, reviewer-core in the reference layout). Use this skill whenever you add or change a backend route, service, repository, adapter, DB query, contract, or DI wiring — and whenever deciding WHERE a piece of logic, an external-tool call (LLM/OpenAI/Anthropic/OpenRouter, GitHub/octokit, git, ripgrep/ast-grep, Postgres), a type, or a validation belongs across layers. Also use when reviewing layering, an import that crosses package/layer boundaries, a leaked Drizzle query, a directly-instantiated SDK client, or business logic creeping into a route. Trigger terms: onion architecture, layer, dependency direction/rule, ports and adapters, repository, service, adapter, composition root, container, dependency inversion, where should this live, layering violation.npx claudepluginhub syukpublic/ai-dev-toolkit --plugin engineering-paved-path