Alexis Le Dain 04c68e483a
Add React language track with agents, skills, rules, and commands (#2024)
* feat(rules): add rules/react/ track

Five rule files mirroring per-language convention (coding-style,
hooks, patterns, security, testing). Each has `paths:` glob
frontmatter for auto-activation when editing matching files.

- coding-style.md: file extensions, naming, JSX, RSC boundary
- hooks.md: React hooks (NOT Claude Code hooks) — rules-of-hooks,
  dep arrays, cleanup, memoization, React 19 additions
- patterns.md: container/presentational split, state location
  decision tree, Suspense + error boundaries, forms, data fetching
- security.md: dangerouslySetInnerHTML, unsafe URL schemes,
  server-action validation, env-var leaks, CSP
- testing.md: RTL queries, userEvent, async, MSW, axe, anti-patterns

Each file extends typescript/* and common/* rules.

* feat(skills): add react-patterns, react-testing, react-performance

Three new skills under skills/ following the SKILL.md convention.

- react-patterns: React 18/19 idioms — hooks discipline, state
  location decision tree, server/client component boundary,
  Suspense + error boundaries, form actions (React 19), data
  fetching matrix, composition recipes, accessibility-first.
- react-testing: React Testing Library + Vitest/Jest, query
  priority order, userEvent, MSW network mocking, axe a11y
  assertions, RTL vs Playwright CT boundary, TDD workflow.
- react-performance: 70-rule performance ruleset adapted from
  Vercel Labs react-best-practices (MIT) across 8 priority
  categories — waterfalls, bundle size, server-side, client
  fetch, re-render, rendering, JS micro, advanced patterns.
  Includes Lighthouse / Web Vitals mapping and attribution to
  upstream.

Cross-links between the three skills and out to frontend-patterns,
accessibility, e2e-testing, tdd-workflow.

* feat(agents): add react-reviewer and react-build-resolver

Two new agents covering React-specific code review and build error
resolution, plus matching .kiro/ mirrors and a routing pointer
edit on typescript-reviewer.

- react-reviewer: slim React-only lanes (hooks rules,
  dangerouslySetInnerHTML, unsafe URL schemes, key prop, state
  mutation, derived-state-in-effect, server/client component
  boundary, accessibility, render performance, Server Action
  validation, env-var leaks). Explicitly delegates generic
  TypeScript/async/Node concerns to typescript-reviewer. Both
  agents should be invoked together on .tsx/.jsx PRs.
- react-build-resolver: React build/bundler/runtime hydration
  failures across Vite, webpack, Next.js, CRA, Parcel, esbuild,
  Bun, Rsbuild. Handles JSX/TSX compile errors, tsconfig fixes,
  Next.js App Router server/client boundary errors, hydration
  mismatches, duplicated React copies, Tailwind/PostCSS pipeline.
- .kiro/agents/react-reviewer.json + react-build-resolver.json:
  Kiro IDE format mirrors following the per-language precedent.
- typescript-reviewer: routing pointer added to its MEDIUM React
  block — defers to /react-review for React-specific concerns
  while keeping its block as fallback for repos that only invoke
  typescript-reviewer.

All agents carry the standard Prompt Defense Baseline stanza.

* feat(commands): add /react-review /react-build /react-test

Three new slash commands invoking the React agents.

- /react-review: invokes react-reviewer. Documents the routing
  rule with typescript-reviewer — both should run together on
  TSX/JSX PRs. Lists CRITICAL/HIGH/MEDIUM rule categories and
  the automated checks (eslint with react-hooks + jsx-a11y,
  tsc --noEmit, npm audit).
- /react-build: invokes react-build-resolver. Documents bundler
  detection, common failure patterns, fix strategy, and stop
  conditions.
- /react-test: enforces TDD with React Testing Library + Vitest
  or Jest, behavior-focused queries, userEvent + MSW patterns,
  axe accessibility assertions, coverage targets.

Each command file has the required description: frontmatter and
follows the per-language command convention (cpp-test, go-test,
kotlin-test, etc.).

* chore: wire react track into manifests and stack mappings

- agent.yaml: add react-patterns, react-performance, react-testing
  to the skills array; add react-build, react-review, react-test to
  the commands array (alphabetically inserted to satisfy the
  ci/agent-yaml-surface sync test).
- config/project-stack-mappings.json: extend the `react` stack
  entry — add "react" to rules array (was ["common","typescript",
  "web"]); add react-patterns, react-performance, react-testing,
  accessibility to the skills array.
- docs/COMMAND-REGISTRY.json: bump totalCommands 75 -> 78; add
  three new entries (react-build, react-review, react-test) with
  primaryAgents / allAgents / skills wiring. react-review's
  allAgents includes typescript-reviewer to reflect the dual-agent
  routing convention.
- CLAUDE.md: add Skills-table row mapping *.tsx / *.jsx /
  components/** to react-patterns + react-testing skills and
  the /react-review, /react-build, /react-test commands.

* chore(catalog): sync counts to 62 agents / 78 commands / 235 skills

Auto-generated via `node scripts/ci/catalog.js --write --text`
after the react track additions:

- 2 new agents: react-reviewer, react-build-resolver (60 -> 62)
- 3 new commands: react-build, react-review, react-test (75 -> 78)
- 3 new skills: react-patterns, react-performance, react-testing
  (232 -> 235)

Files updated by the catalog sync:
- .claude-plugin/plugin.json description string
- .claude-plugin/marketplace.json plugin description
- README.md quick-start summary, project tree, feature parity tables
- README.zh-CN.md quick-start summary
- AGENTS.md project structure summary
- docs/zh-CN/README.md parity table
- docs/zh-CN/AGENTS.md project structure summary

All counts now match the filesystem catalog (verified by
ci/catalog.test.js).

* feat(kiro): add react agent markdown companions to JSON entries

* feat(kiro): add react skills into manifests

* fix(ci): sync catalog counts, registry, and package files for react track

- .claude-plugin/{plugin,marketplace}.json: bump description counts to 62/235/78
- docs/COMMAND-REGISTRY.json: regenerate to include quality-gate and react commands
- package.json: add skills/react-{patterns,performance,testing}/ to files allowlist so npm-publish-surface aligns with install-modules manifest

* fix(react): address PR #2024 review feedback

Critical:
- Remove undefined/.claude/session-aliases.json containing __proto__ prototype-pollution
  fixture committed by accident in a7333c14

High:
- agents/react-build-resolver.md: replace brittle `test -o $(grep -l ...)` and
  `test -a -n $(grep ...)` detection with explicit `{ ... || grep -q ...; }` so
  bundler detection no longer breaks when grep returns empty
- agents/react-build-resolver.md: drop hardcoded `npm i react@^19 react-dom@^19`
  remediation; replace with version-agnostic pair-upgrade note that honors the
  project's installed major (17/18/19) — surgical fix principle
- commands/react-review.md: guard `tsc --noEmit -p tsconfig.json` with
  `[ -f tsconfig.json ] &&` so the review skips cleanly on JS-only projects

Medium:
- rules/react/security.md: correct the React-18-blocks-javascript-URL claim
  (React only warns in dev; production navigation is not blocked)
- rules/react/security.md: correct CRA env-var exposure row (CRA exposes
  REACT_APP_*, NODE_ENV, PUBLIC_URL — not 'all' variables)
- skills/react-testing/SKILL.md: instantiate QueryClient once outside the
  wrapper closure so React Query cache survives re-renders (flaky-test fix)
- skills/react-testing/SKILL.md: restore console.error spy with mockRestore()
  in a try/finally so the mock does not leak across tests
- commands/react-test.md: switch outer example-session fence to 4 backticks
  so the inner ```tsx/```bash blocks don't prematurely terminate it

* fix(kiro): mirror react-build-resolver react 19 conditional remediation

Discussion r3272907106 flagged the kiro json variant still carrying the hardcoded
'npm i react@^19 react-dom@^19' line that the .md companion already dropped.
Replace with the same conditional, version-agnostic guidance so both variants
stay in sync.

* fix(react): bump react-build example session fence to 4 backticks

Discussion r3272907144 flagged the same nested-fence issue in
commands/react-build.md that we fixed earlier in commands/react-test.md.
The outer triple-backtick text block was being prematurely terminated by
the inner bash/tsx fences inside the Example Session.

* fix(react): bump react-review example usage fence to 4 backticks

Discussion r3272907201 flagged the same nested-fence issue in
commands/react-review.md. The outer triple-backtick text block was
being prematurely terminated by the inner tsx/ts fences inside the
Example Usage transcript.

* fix(docs): clarify commands row as legacy shims in feature parity table

Discussion r3272912003: README comparison table said 'PASS: 78 commands'
while the install-section and quick-start prose use 'legacy command shims'.
Aligned the comparison-table cell to 'PASS: 78 commands (legacy shims)' so
the count word survives the catalog-validator regex while making the legacy
nature explicit.

Widened the catalog comparison-table commands regex to tolerate an optional
parenthetical after the count word, so both the existing 'X commands' and
the new 'X commands (legacy shims)' phrasings validate without breaking
older READMEs/translations.

* Update rules/react/security.md

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* fix(react): guard tsc in react-build-resolver diagnostic commands

Discussion r3288910205: the agent prompt instructed an unconditional
'tsc --noEmit -p tsconfig.json', which adds noise (or hard-fails) on
JavaScript-only projects with no tsconfig.json or no installed TypeScript.

Replaced with 'test -f tsconfig.json && npx --yes tsc --noEmit -p tsconfig.json'
in both variants:
- agents/react-build-resolver.md
- .kiro/agents/react-build-resolver.json (prompt string mirrored)

Mirrors the same guard already applied to commands/react-review.md in de135f61.

* fix(react): pin tsc resolution to local install in build resolver

Discussion r3289054157: previous fix used 'npx --yes tsc' which auto-installs
the latest TypeScript from npm when none is local, producing version drift
and non-reproducible typecheck results across machines.

Switched to 'npx --no-install tsc' in both variants so the diagnostic uses
only the project's pinned TypeScript and fails fast if it isn't installed:
- agents/react-build-resolver.md
- .kiro/agents/react-build-resolver.json (prompt string mirrored)

* feat(counts): resolve counts for agents, skills...

* fix(ci): regen command registry for golang-testing entry

Removes stale kotlin-patterns entry to satisfy command-registry:check.

* fix: keep local Claude settings out of React track PR

---------

Co-authored-by: AlexisLeDain <a.ledain@docoon.com>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
Co-authored-by: Affaan Mustafa <affaan@dcube.ai>
2026-05-28 07:32:52 -04:00

6.9 KiB

paths
paths
**/*.test.tsx
**/*.test.jsx
**/*.spec.tsx
**/*.spec.jsx
**/__tests__/**/*.ts
**/__tests__/**/*.tsx

React Testing

This file extends typescript/testing.md and common/testing.md with React specific content.

Library Choice

  • React Testing Library (RTL) — the standard for component testing. Tests behavior through the rendered DOM.
  • Vitest — preferred runner for new Vite-based projects. Faster than Jest, native ESM, same API.
  • Jest — still the default for Next.js / CRA projects. RTL works identically.
  • Playwright Component Testing — when component tests need a real browser engine (animation, layout, complex events)
  • Cypress Component Testing — alternative real-browser component runner

Pick one component test runner per project — do not mix RTL + Playwright CT in the same repo.

Core Principle

Test what the user sees and does, not implementation details.

  • Query by accessible role first, then label, then text — fall back to data-testid only when nothing else fits
  • Never assert on internal state, props passed to children, or which hooks were called
  • Refactor without breaking tests = the test was testing behavior; that is the goal

Query Priority

RTL exposes queries in three families. Use this priority order top-down:

  1. Accessible to everyone

    • getByRole(role, { name }) — primary choice
    • getByLabelText — for form inputs
    • getByPlaceholderText — when no label is available (and add a label)
    • getByText — for non-interactive text
    • getByDisplayValue — for form fields with a current value
  2. Semantic queries

    • getByAltText — for images
    • getByTitle — last resort, low accessibility value
  3. Test IDs

    • getByTestId("some-id") — escape hatch only, when none of the above work

getBy* throws when no match. queryBy* returns null (use for asserting absence). findBy* returns a promise (use for async).

User Interaction

Prefer userEvent over fireEvent. userEvent simulates real browser sequences (focus, keydown, beforeinput, input, keyup) — fireEvent dispatches a single synthetic event.

import userEvent from "@testing-library/user-event";

test("submits the form", async () => {
  const user = userEvent.setup();
  render(<UserForm onSubmit={handleSubmit} />);

  await user.type(screen.getByLabelText("Email"), "user@example.com");
  await user.click(screen.getByRole("button", { name: /save/i }));

  expect(handleSubmit).toHaveBeenCalledWith({ email: "user@example.com" });
});
  • Always await userEvent calls — they are async
  • Call userEvent.setup() once at the top of each test, then reuse the returned user

Async Assertions

// WRONG: synchronous query for async-rendered content
expect(screen.getByText("Loaded")).toBeInTheDocument();   // throws — not in DOM yet

// CORRECT: findBy* (returns a promise, retries)
expect(await screen.findByText("Loaded")).toBeInTheDocument();

// CORRECT: waitFor for non-element assertions
await waitFor(() => expect(saveSpy).toHaveBeenCalled());
  • findBy* for async element appearance
  • waitFor for async expectations on side effects or other matchers
  • Never setTimeout + assertion — flaky

Network Mocking with MSW

Use Mock Service Worker for any test that hits a network boundary. MSW runs at the network layer, so the component, hooks, and fetch library all behave as in production.

// test setup
import { setupServer } from "msw/node";
import { http, HttpResponse } from "msw";

const server = setupServer(
  http.get("/api/users/:id", ({ params }) =>
    HttpResponse.json({ id: params.id, name: "Alice" }),
  ),
);

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

Per-test override:

test("renders error on 500", async () => {
  server.use(http.get("/api/users/:id", () => new HttpResponse(null, { status: 500 })));
  render(<UserPage id="1" />);
  expect(await screen.findByText(/something went wrong/i)).toBeInTheDocument();
});

Avoid Snapshot Tests for Components

Snapshots of rendered output are brittle, hard to review, and rubber-stamped by reviewers. Use them only for:

  • Pure data serialization (e.g., a transformer that produces a stable string)
  • Catching unintended regressions in non-visual output

For component visual regression, use Playwright / Cypress / Percy screenshots — actual visual diffs, not DOM diffs.

Test Setup Helpers

Wrap providers once:

function renderWithProviders(ui: React.ReactElement) {
  return render(
    <QueryClientProvider client={new QueryClient()}>
      <ThemeProvider theme={lightTheme}>
        <Router>{ui}</Router>
      </ThemeProvider>
    </QueryClientProvider>,
  );
}

Export from test-utils.tsx and use everywhere.

Custom Hook Testing

Use renderHook from RTL:

import { renderHook, act } from "@testing-library/react";

test("useCounter increments", () => {
  const { result } = renderHook(() => useCounter());
  act(() => result.current.increment());
  expect(result.current.count).toBe(1);
});
  • Always wrap state-changing calls in act
  • Always test through the public hook API, not internal implementation

Accessibility Assertions

import { axe } from "vitest-axe";   // or jest-axe

test("UserCard has no a11y violations", async () => {
  const { container } = render(<UserCard user={mockUser} />);
  expect(await axe(container)).toHaveNoViolations();
});

Run axe assertions in component tests — catches missing labels, ARIA misuse, color contrast (limited).

When to Reach for Playwright / Cypress

Component test with RTL + JSDOM cannot:

  • Test real layout (flexbox, grid, viewport-dependent rendering)
  • Test scrolling, drag-and-drop, paste from clipboard
  • Test browser-native animation, CSS transitions
  • Test cross-frame interactions (iframes, popups)

For those, use Playwright Component Testing or end-to-end Playwright/Cypress runs. See e2e-testing skill.

Coverage Targets

Layer Target
Pure utility functions ≥90%
Custom hooks ≥85%
Components (presentational) ≥80% — behavior, not lines
Container components ≥70% — golden paths + error states
Pages (E2E covered separately) Smoke test per route minimum

Anti-Patterns

  • Asserting on container.querySelector — bypasses accessibility queries
  • Asserting on number of renders — implementation detail
  • Mocking React hooks (jest.mock("react", ...)) — refactor the component instead
  • Mocking child components by default — tests the integration, not the parent in isolation
  • Manual act() warnings ignored — they indicate real bugs

Skill Reference

See skills/react-testing/SKILL.md for end-to-end test examples, MSW patterns, and accessibility test scaffolding.