Skip to content
Skills Library
Programming · Testing

react-testing

/react-testing

React component, hook and page tests - Testing Library on Vitest or Jest, MSW, axe, and where Playwright takes over. Use when writing, fixing or setting up *.test.tsx / *.spec.tsx. Process and coverage: tdd-workflow.

Licence
MIT
Last repository change
05.11.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
2
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 05.11.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

React component, hook and page tests - Testing Library on Vitest or Jest, MSW, axe, and where Playwright takes over. Use when writing, fixing or setting up *.test.tsx / *.spec.tsx. Process and coverage: tdd-workflow.

Original author description

React component, hook and page tests - Testing Library on Vitest or Jest, MSW, axe, and where Playwright takes over. Use when writing, fixing or setting up *.test.tsx / *.spec.tsx. Process and coverage: tdd-workflow.

How it works

  1. Principle
  2. Runners
  3. Queries
  4. Interaction and async
  5. Network: MSW
  6. Providers and hooks
  7. Accessibility
  8. Snapshots
  9. Component test or browser test
  10. Anti-patterns
Original SKILL.md headings · 102 lines, 693 words
SKILL.md preview
---
name: react-testing
description: "React component, hook and page tests - Testing Library on Vitest or Jest, MSW, axe, and where Playwright takes over. Use when writing, fixing or setting up *.test.tsx / *.spec.tsx. Process and coverage: tdd-workflow."
---

# react-testing

Test process and coverage: `tdd-workflow`. Browser checks: `browser-qa`.

## Principle

Test what the user sees and does.

- Render with the providers used in production. Interact through accessible queries and `userEvent`. Assert visible output and observable effects (callback called, request sent).
- Never assert on state, props passed to children, which hooks ran, render counts, or DOM structure users cannot perceive.
- A behavior-preserving refactor must keep tests green; a test that breaks checked implementation.

## Runners

| Runner | Use for |
|---|---|
| Vitest | New and Vite-based projects; Jest-compatible API, native ESM |
| Jest | Repos already on Jest; Next.js ships `next/jest` |
| Playwright Component Testing | Components that need a real browser engine |
| Cypress Component Testing | Same, when the repo already uses Cypress |
| Playwright | E2E of critical user flows (Cypress only if already in use) |

- One component-test runner per repo, unless the lanes are clearly split.
- React 19 needs React Testing Library 16.1+. Install `@testing-library/dom` next to it (peer dependency since 16.0).

## Queries

Prefer, top down:

1. `getByRole(role, { name })`; `getByLabelText` for fields; `getByPlaceholderText` only when there is no label (then add one); `getByText` for non-interactive text; `getByDisplayValue`.
2. `getByAltText` for images; `getByTitle` (weak).
3. `getByTestId` when nothing above fits.

- `getBy*` throws on no match, `queryBy*` returns `null` (assert absence), `findBy*` returns a promise (async appearance).
- No `container.querySelector`: it lets tests pass where users fail.

## Interaction and async

- `userEvent`, not `fireEvent`: it plays the full browser sequence (focus, keys, input); `fireEvent` sends one event.
- `const user = userEvent.setup()` once per test, before render; `await` every call.
- Content that arrives later: `await screen.findBy*` (a sync `getBy*` throws).
- Side effects: `await waitFor(() => expect(spy).toHaveBeenCalled())`.
- Removal: `await waitForElementToBeRemoved(() => screen.queryByText('Loading'))`.
- Never `setTimeout` then assert.
- Treat `act()` warnings as bugs: an unawaited update or an update after unmount.

## Network: MSW

Mock HTTP at the network layer; components, hooks and the fetch client run unchanged.

```ts
// test/setup.ts
import { setupServer } from 'msw/node'
import { http, HttpResponse } from 'msw'

export const server = setupServer(
  http.get('/api/items/:id', ({ params }) => HttpResponse.json({ id: params.id, title: 'Desk' })),
)
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
afterEach(() => server.resetHandlers())
afterAll(() => server.close())
```

- `onUnhandledRequest: 'error'` fails any test that makes an unmocked request.
- Per test: `server.use(...)`, e.g. return `new HttpResponse(null, { status: 500 })` and assert the error UI.

## Providers and hooks

- One `renderWithProviders` in `test-utils.tsx` that also re-exports Testing Library; import from it everywhere.
- New `QueryClient` per test with `retry: false`, created outside the wrapper component (inside, it is rebuilt each render and drops its cache). In-memory router for routed components.
- Hooks: `renderHook(() => useX(arg), { wrapper })`; wrap state changes in `act`; assert only the returned API.

## Accessibility

- Every interactive component: `expect(await axe(container)).toHaveNoViolations()` (`jest-axe`; `expect.extend(toHaveNoViolations)` in setup, works with Vitest). Catches missing labels, invalid ARIA, missing alt text, heading order.
- JSDOM has no real CSS, so contrast results here are unreliable; check contrast in the browser (`browser-qa`). Criteria: `accessibility`.

## Snapshots

- Do not snapshot rendered components: they break on styling, get approved unread, and pin structure, not behavior.
- Allowed for stable non-visual output: serializers, generated config.
- Visual regression uses screenshots (`browser-qa`), not DOM strings.

## Component test or browser test

JSDOM has no real layout (flex, grid, viewport), CSS animation or transitions, scrolling, drag-and-drop, clipboard, iframes, popups, downloads or cross-origin flows.

- Hook, presentational component, form logic: Testing Library.
- Layout-dependent component, or a browser API JSDOM lacks: Playwright Component Testing.
- Async Server Component (Next.js App Router): Vitest and Jest cannot render it; cover it with E2E. Sync Server and Client Components unit-test normally.
- Flow across pages: Playwright E2E.

## Anti-patterns

- Mocking React or its hooks (`vi.mock('react')`): refactor the component.
- Mocking child components by default; mock only children with heavy side effects.
- Mutable state shared between tests.
- A test that stays green when the code under test is broken.

Worked examples (provider helper, form with MSW, error boundary, Suspense): [references/examples.md](references/examples.md).
Files in this package (2)
  • SKILL.md 5 KB
  • references/examples.md 2 KB

Versions

RepositoryScoreLicence
This page · ssvinar/senior-agent-skills100MIT
ahmet-cetinkaya/dotfiles100MIT
mintuz/claude-plugins100MIT
Sanit-mann/The-Insectoids100MIT
aratkruglik/claude-sdlc100MIT
getsentry/sentry100Apache-2.0
HoangNguyen0403/agent-skills-standard100MIT
claude-dev-suite/claude-dev-suite100MIT
qualcomm/qualcomm-ui100BSD-3-Clause

Database snapshot: 13.11.2026 · package version 9ff5087cd911 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100nextjs-testing
    Write Jest or Vitest unit tests with React Testing Library and Playwright E2E tests for Next.js projects. Use when testing components with RTL, mocking APIs with MSW, or creating Playwright user flow tests.
  • 100testing-react
    Writes React/TypeScript tests using Vitest and React Testing Library. Use when "write react tests", "vitest", "component test", "hook test", "RTL", "testing library", "snapshot test", or testing React components, hooks, and utilities.
  • 100react-vitest
    Use when adding or improving tests in a React project that uses Vitest — covers component testing with Testing Library, mocking hooks, and coverage configuration.
  • 90frontend-testing
    Testing strategy and setup for TypeScript frontends: Vitest with Testing Library for React and Next.js, the Angular Vitest builder (@angular/build:unit-test) with TestBed and component harnesses, MSW for API mocking, Playwright for end-to-end, coverage thresholds and CI wiring.…
  • 100vitest-rtl-msw-patterns
    Frontend testing with Vitest, React Testing Library, MSW v2, plus contract tests where Zod schemas mirror backend Pydantic models. Use for test infra setup, component tests, or mocking API requests.
  • 100testing
    Writing frontend tests for the nvcf-ui app — Vitest, Testing Library, MSW, and project-specific render helpers. Use when creating test files, writing component tests, setting up MSW handlers in tests, deciding which render helper to use, or when the user is adding or modifying a…

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.