Org Skills

react-testing

Design a React web test strategy and write the tests — Vitest 5 with React Testing Library in jsdom or Browser Mode, MSW 2 for the network, testing hooks, Suspense and error boundaries, async Server Components and Server Actions, Storybook 10 play functions with the Vitest addon, and Playwright journeys.

Download .zip Raw Source
When agents use itUse this whenever the user asks how to test a React component, hook, form, page, loader or Server Action; asks "what should I test"; sets up vitest.config.ts, a test setup file, renderWithProviders or MSW handlers; asks about getByRole vs getByTestId, userEvent, findBy vs waitFor, fake timers, vi.mock hoisting, act() warnings, coverage thresholds or a flaky test that only fails in CI. Also use it when generating tests for React code the user just wrote, even if they do not say the word "test". For React Native use react-native-testing.

Install

Copilot (VS Code, Visual Studio, Copilot CLI and github.com) reads skills from the repository — commit them so the whole team gets them.

npx skills add AGCO-Global/org-skills --skill react-testing -a github-copilot
# or with the org installer (adds .github/skills/react-testing):
npx -y github:AGCO-Global/org-skills add skill react-testing

Uses the open skills CLI. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, OpenCode, Windsurf and 60+ others — it asks which agent to install into.

npx skills add AGCO-Global/org-skills --skill react-testing
# user-level instead of project-level:
npx skills add AGCO-Global/org-skills --skill react-testing -g

Installs the frontend-react-skills plugin, which bundles all Frontend / React skills and keeps them updated.

/plugin marketplace add AGCO-Global/org-skills
/plugin install frontend-react-skills@org-skills
# or just this skill, in this repository:
npx skills add AGCO-Global/org-skills --skill react-testing -a claude-code

Use Download .zip above, then upload it under Customize → Skills → Upload skill. Team and Enterprise admins can sync this repo as a plugin marketplace instead.

Installs into .agents/skills/, which Codex reads.

npx skills add AGCO-Global/org-skills --skill react-testing -a codex

Installs into Cursor's skills folder.

npx skills add AGCO-Global/org-skills --skill react-testing -a cursor

Installs into Gemini CLI's skills folder.

npx skills add AGCO-Global/org-skills --skill react-testing -a gemini-cli

Nothing to install. Press Download .zip above, unzip it, and drop the react-testing folder into your tool's skills folder — .claude/skills/, .github/skills/, .cursor/skills/ or .agents/skills/. Step-by-step, per tool: How to use it. For any other tool with rules or custom prompts, Copy SKILL.md and paste it in — it is plain Markdown.

The npx commands need Node.js 20+ and use your normal git sign-in to GitHub, so they work while the repository is private. Without Node.js, see the No Node.js tab — a skill is a folder of Markdown, so copying it in works just as well.

Skill contents

React Testing

Targets: Vitest 5 · React Testing Library 16 · MSW 2 · Storybook 10 · Playwright · React 19.2 · Verified: 2026-09 against https://vitest.dev, https://testing-library.com, https://mswjs.io, https://storybook.js.org

Tests exist so the team can refactor without fear. Optimise for confidence per minute of maintenance: test the behaviour a user can observe, through the real component tree, with only the network faked. Coverage percentage is a smell detector, never a goal. Web only — for React Native use react-native-testing.

1. Decide first

Question Default Change when
Which layer? Component/integration test of a feature slice with RTL + MSW (~60% of the suite) Pure domain logic in model/ → plain unit test, no React. A cross-page journey → one Playwright test
Runner Vitest 5 (vitest.config.ts next to the Vite/Next config) Legacy repo already on Jest → keep Jest; the RTL rules are identical
Environment jsdom — fast, no layout Test depends on real layout, focus order, IntersectionObserver, drag or CSS → Browser Mode with vitest-browser-react
Network MSW 2 handlers, onUnhandledRequest: 'error' Third-party SDK with no HTTP surface (analytics, flags) → vi.mock the module
Query getByRole(name) No accessible name exists → fix the component first; getByTestId only with a comment saying why
Interaction userEvent.setup() Only when userEvent cannot express it (scroll, paste of binary) → fireEvent
Component states Happy path, validation/error, loading, empty — one it each A state is unreachable by users → delete the state, not the test
End-to-end 5–15 journeys in Playwright against a production build Storybook already covers the visual states of a primitive → do not duplicate

2. Setup that prevents most flakiness

Three files do the work: vitest.config.ts, src/test/setup.ts, and src/test/render.tsx. Full contents, Browser Mode config and the CI pipeline shape are in references/setup.md. The rules that matter:

  • setupFiles starts the MSW server with onUnhandledRequest: 'error' — the single most valuable line, because a real network call then fails loudly instead of hanging.
  • server.resetHandlers() in afterEach. RTL cleans up automatically when afterEach is globally available (globals: true, or the vitest setup import), so do not call cleanup() by hand.
  • @testing-library/react 16 needs @testing-library/dom installed explicitly as a peer dependency.
  • One renderWithProviders helper wraps the real QueryClientProvider (retry: false), router, theme and i18n. Nobody hand-wires providers in a test file.

3. Component tests — the rules

  • Query by role and accessible name first. screen.getByRole('button', { name: /save/i }) tests what users and screen readers get, and fails when accessibility breaks.
  • findBy* for appearance, waitFor for disappearance or a non-DOM assertion. Never setTimeout in a test.
  • Assert outcomes, not implementation. Never assert that a setter ran; assert the DOM changed. Never assert that a component is memoised — with the React Compiler on, that is not observable.
  • One behaviour per test, named as a sentence: it('shows a validation error when email is empty on submit').
  • Do not test the library. Not "React Hook Form validates" but "our schema produces this message on this field".
import { http, HttpResponse } from 'msw';
import userEvent from '@testing-library/user-event';
import { screen } from '@testing-library/react';
import { server } from '@/test/msw/server';
import { renderWithProviders } from '@/test/render';
import { Checkout } from './Checkout';

it('submits the order and shows the confirmation', async () => {
  server.use(http.post('/api/orders', () => HttpResponse.json({ id: '42' }, { status: 201 })));
  const user = userEvent.setup();
  renderWithProviders(<Checkout />);

  await user.type(screen.getByLabelText(/email/i), 'a@b.com');
  await user.click(screen.getByRole('button', { name: /place order/i }));

  expect(await screen.findByText(/order #42 confirmed/i)).toBeInTheDocument();
});

4. Mocking, time and modules

  • Network → MSW. Handlers in src/test/msw/handlers/<feature>.ts, mirroring the real payload shape, reused by Storybook and Playwright. Override per test with server.use(...); add an error case with HttpResponse.json({...}, { status: 500 }).
  • Time → fake timers, and tell userEvent about them — without this every user.type hangs forever:
vi.useFakeTimers();
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
// … then await vi.runAllTimersAsync() to flush a debounce

Restore with vi.useRealTimers() in afterEach.

  • Modules → vi.mock only for true externals (analytics, feature flags, window.matchMedia). vi.mock calls are hoisted above imports, so any variable a factory uses must be created with vi.hoisted(() => …).
  • Never mock useState, useEffect, the query client, or your own hooks — mocking your own module is a design smell; inject through props or context instead.

5. Hooks, Suspense and error boundaries

  • Test a hook through a component that uses it. For a genuinely shared hook, renderHook with a wrapper, then await waitFor(() => expect(result.current.isSuccess).toBe(true)).
  • Suspense: render inside the real boundary, assert the fallback is present, then await screen.findBy… for the resolved UI.
  • Error boundary: make the MSW handler return 500, assert the designed error UI and that the retry control refetches (add a second server.use returning 200).
  • Accessibility: assert with axe (vitest-axe in jsdom, @axe-core/playwright in end-to-end) on at least one test per feature screen.

6. Server code (Next.js 16, React Router v8)

An async Server Component is an async function returning JSX: render(await Page({ params: Promise.resolve({ id: '1' }) })). A Server Action is a plain async function — call it directly with FormData and mock cookies()/headers(). A 'use cache' function is tested by calling it. Loaders and actions are functions too: pass a Request and assert on the returned data. Details and samples: references/server-testing.md.

7. Deliverable format

## Behaviours to cover
1. <observable behaviour> — happy / error / empty / loading

## Tests
<file path>  (imports included, one it() per behaviour)

## Fixtures and handlers
<MSW handlers added or reused>

## How to run
<command>  — and what fails if the behaviour regresses

Checklist

  • Behaviours listed before any test code was written
  • Queries are role/label based; every getByTestId has a justifying comment
  • userEvent.setup() used; with fake timers it passes advanceTimers
  • Network faked with MSW, onUnhandledRequest: 'error'; no hook or query-client mocks
  • Happy path, validation/error, loading and empty states each asserted
  • Async awaited via findBy*/waitFor — no setTimeout, no hand-written act()
  • Existing renderWithProviders and handlers reused, not duplicated
  • No snapshot of a whole component tree; snapshots only for small serialisable values
  • Suite passes when run in a different order and on a second run (no shared mutable state)
  • CI runs type check, unit/component, Storybook (Vitest addon) and Playwright with traces on retry

Anti-patterns

  • Snapshotting the rendered tree → assert the two or three things that matter; a diff nobody reads is not a test.
  • getByTestId as the first query → give the element a role and an accessible name.
  • fireEvent.change for typing → await user.type, which fires the same sequence a real user does.
  • Wrapping assertions in act() by hand → await findBy* / await user.click; RTL already wraps.
  • Mocking your own hook to "isolate" the component → render the real hook and fake the network.
  • Asserting render counts or memo behaviour → the compiler makes that unobservable; assert output.
  • Skipping a flaky test → fix the cause (unreset handler, real timer, shared state) or delete it.
  • @storybook/test imports → storybook/test since Storybook 9.

Go deeper

  • references/setup.md — vitest.config.ts for jsdom and Browser Mode, setup file, renderWithProviders, MSW server, coverage thresholds and the CI pipeline shape.
  • references/server-testing.md — async Server Components, Server Actions with mocked cookies(), 'use cache' functions, React Router loaders/actions and middleware.
  • references/e2e-and-storybook.md — Playwright journeys, storageState, traces and sharding; Storybook 10 play functions, @storybook/addon-vitest, @storybook/addon-a11y.
  • Sibling skills: react-development (the code under test), react-architecture, react-performance, frontend-code-review, react-native-testing (mobile).

References

Deeper material the agent loads only when needed.