[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M70H03A9HC78CV7WFXBWA49N":3,"skill-same:01M70H03A9HC78CV7WFXBWA49N":79},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":29,"publishedAt":50,"linkOnly":51,"markdownContent":52,"markdownBody":53,"frontMatter":54,"refName":57,"commitSha":58,"skillDirectory":59,"forksCount":60,"repositoryHtmlUrl":61,"repositoryHomepageUrl":6,"ownerHtmlUrl":62,"ownerBlogUrl":6,"ownerDescription":63,"updatedAt":64,"install":65,"resources":78},"01M70H03A9HC78CV7WFXBWA49N","react-testing",null,"React component testing with React Testing Library, Vitest\u002FJest, MSW for network mocking, accessibility assertions with axe, and the decision boundary between component tests and Playwright\u002FCypress end-to-end runs. Use when writing or fixing tests for React components, hooks, or pages.","mdnaimul22\u002Fhuman-skills","mdnaimul22","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F64520358?v=4","01M70FH95MH2H796Q01TYSFZ03","Naimul","01M70FH96798CQR4YHA13F17GA",3,"MIT","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Freact-testing\u002FSKILL.md",[18,23,26],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000008","测试与质量","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000009","前端开发",{"categoryNo":27,"categoryName":28,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49],"react","react testing","testing","decision","when","for","react testing library","msw","cypress","end","jest","hooks","vitest","network","library","testing library","component","react components","components","writing","2026-11-10 10:12:30",false,"---\nname: react-testing\ndescription: React component testing with React Testing Library, Vitest\u002FJest, MSW for network mocking, accessibility assertions with axe, and the decision boundary between component tests and Playwright\u002FCypress end-to-end runs. Use when writing or fixing tests for React components, hooks, or pages.\nmetadata:\n  origin: ECC\n---\n\n# React Testing\n\nComprehensive React testing patterns for behavior-focused component tests, custom hook tests, accessibility assertions, and network-level mocking.\n\n## When to Activate\n\n- Writing tests for React components, custom hooks, or pages\n- Adding test coverage to legacy untested components\n- Migrating from Enzyme or class-component-era patterns to React Testing Library\n- Setting up Vitest or Jest for a new React project\n- Mocking HTTP requests in tests\n- Asserting accessibility violations\n- Deciding which tests belong in RTL vs Playwright Component Testing vs full E2E\n\n## Core Principle\n\nTest what the user sees and does, not implementation details.\n\nA test should:\n\n- Render the component with the same providers it has in production\n- Interact with it via accessible queries (role, label) and `userEvent`\n- Assert visible output and observable side effects (callback fired, request sent)\n\nA test should NOT:\n\n- Inspect component state, props passed to children, or which hooks were called\n- Mock React itself or framework hooks\n- Assert on the number of renders or DOM structure beyond what affects users\n\n## Library Choice\n\n| Runner | When | Note |\n|---|---|---|\n| **Vitest** | Vite, Remix, modern setups | Faster, native ESM, Jest-compatible API |\n| **Jest** | Next.js, CRA, established repos | Default for many React projects |\n| **Playwright Component Testing** | Real browser engine needed | Use when JSDOM lacks the required feature |\n| **Cypress Component Testing** | Real browser, Cypress already in use | Alternative to Playwright CT |\n\nPick one. Do not run RTL + Vitest AND Playwright CT in the same repo unless you have a clear lane separation.\n\n## Query Priority\n\nReact Testing Library exposes queries in three tiers — use top-down:\n\n1. **Accessible to everyone**: `getByRole`, `getByLabelText`, `getByPlaceholderText`, `getByText`, `getByDisplayValue`\n2. **Semantic**: `getByAltText`, `getByTitle`\n3. **Test IDs (escape hatch)**: `getByTestId`\n\n```tsx\n\u002F\u002F Best\nscreen.getByRole(\"button\", { name: \u002Fsave\u002Fi });\n\n\u002F\u002F OK for inputs\nscreen.getByLabelText(\"Email\");\n\n\u002F\u002F Last resort\nscreen.getByTestId(\"save-btn\");\n```\n\nVariants:\n\n- `getBy*` — throws if no match\n- `queryBy*` — returns `null` (use for \"assert absence\")\n- `findBy*` — async, returns a Promise (use for elements that appear after async work)\n\n## User Interaction with `userEvent`\n\n```tsx\nimport userEvent from \"@testing-library\u002Fuser-event\";\n\ntest(\"submits the form\", async () => {\n  const user = userEvent.setup();\n  const onSubmit = vi.fn();\n  render(\u003CUserForm onSubmit={onSubmit} \u002F>);\n\n  await user.type(screen.getByLabelText(\"Email\"), \"user@example.com\");\n  await user.click(screen.getByRole(\"button\", { name: \u002Fsave\u002Fi }));\n\n  expect(onSubmit).toHaveBeenCalledWith({ email: \"user@example.com\" });\n});\n```\n\n- Always `await` userEvent calls\n- Call `userEvent.setup()` once per test, reuse the returned `user`\n- `userEvent` simulates a real browser sequence; `fireEvent` dispatches a single synthetic event — prefer `userEvent`\n\n## Async Patterns\n\n```tsx\n\u002F\u002F Element that appears after async work\nexpect(await screen.findByText(\"Loaded\")).toBeInTheDocument();\n\n\u002F\u002F Side effect assertion\nawait waitFor(() => expect(saveSpy).toHaveBeenCalled());\n\n\u002F\u002F Element that should disappear\nawait waitForElementToBeRemoved(() => screen.queryByText(\"Loading\"));\n```\n\nNever `setTimeout` + assertion — flaky. Use the matchers above.\n\n## Network Mocking with MSW\n\nMock Service Worker mocks at the network layer. The component, hooks, and fetch library all behave exactly as in production.\n\n### Setup\n\n```ts\n\u002F\u002F test\u002Fsetup.ts\nimport { setupServer } from \"msw\u002Fnode\";\nimport { http, HttpResponse } from \"msw\";\n\nexport const handlers = [\n  http.get(\"\u002Fapi\u002Fusers\u002F:id\", ({ params }) =>\n    HttpResponse.json({ id: params.id, name: \"Alice\" }),\n  ),\n  http.post(\"\u002Fapi\u002Fusers\", async ({ request }) => {\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(() => server.listen({ onUnhandledRequest: \"error\" }));\nafterEach(() => server.resetHandlers());\nafterAll(() => server.close());\n```\n\nConfigure `onUnhandledRequest: \"error\"` so any unmocked request fails the test loudly — silent passes are worse than red.\n\n### Per-test override\n\n```tsx\ntest(\"renders error on 500\", async () => {\n  server.use(\n    http.get(\"\u002Fapi\u002Fusers\u002F:id\", () => new HttpResponse(null, { status: 500 })),\n  );\n  render(\u003CUserPage id=\"1\" \u002F>);\n  expect(await screen.findByText(\u002Fsomething went wrong\u002Fi)).toBeInTheDocument();\n});\n```\n\n## Provider Wrapping\n\nWrap providers once in a `test-utils.tsx`:\n\n```tsx\n\u002F\u002F test-utils.tsx\nimport { render, RenderOptions } from \"@testing-library\u002Freact\";\nimport { QueryClient, QueryClientProvider } from \"@tanstack\u002Freact-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    \u003CQueryClientProvider client={queryClient}>\n      \u003CThemeProvider theme={lightTheme}>\n        \u003CMemoryRouter>{ui}\u003C\u002FMemoryRouter>\n      \u003C\u002FThemeProvider>\n    \u003C\u002FQueryClientProvider>,\n    options,\n  );\n}\n\nexport * from \"@testing-library\u002Freact\";\n```\n\nThen `import { renderWithProviders, screen } from \"test-utils\"` in every test file.\n\n## Custom Hook Testing\n\n```tsx\nimport { renderHook, act } from \"@testing-library\u002Freact\";\n\ntest(\"useCounter increments and decrements\", () => {\n  const { result } = renderHook(() => useCounter(0));\n\n  expect(result.current.count).toBe(0);\n\n  act(() => result.current.increment());\n  expect(result.current.count).toBe(1);\n\n  act(() => result.current.decrement());\n  expect(result.current.count).toBe(0);\n});\n\ntest(\"useCounter accepts initial value\", () => {\n  const { result } = renderHook(() => useCounter(10));\n  expect(result.current.count).toBe(10);\n});\n\ntest(\"useUser fetches user data\", async () => {\n  \u002F\u002F Instantiate QueryClient ONCE per test outside the wrapper so it survives re-renders.\n  \u002F\u002F 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 }) => (\n    \u003CQueryClientProvider client={queryClient}>{children}\u003C\u002FQueryClientProvider>\n  );\n\n  const { result } = renderHook(() => useUser(\"1\"), { wrapper });\n\n  await waitFor(() => expect(result.current.isSuccess).toBe(true));\n  expect(result.current.data).toEqual({ id: \"1\", name: \"Alice\" });\n});\n```\n\n- Wrap state-changing calls in `act`\n- Test through the hook's public API only\n- For hooks that use context, pass a `wrapper`\n\n## Accessibility Assertions\n\n```tsx\nimport { axe, toHaveNoViolations } from \"jest-axe\"; \u002F\u002F or vitest-axe\nexpect.extend(toHaveNoViolations);\n\ntest(\"UserCard has no a11y violations\", async () => {\n  const { container } = render(\u003CUserCard user={mockUser} \u002F>);\n  expect(await axe(container)).toHaveNoViolations();\n});\n```\n\nRun axe in component tests for every interactive component. Catches:\n\n- Missing labels on form inputs\n- Invalid ARIA usage\n- Poor color contrast (limited — JSDOM has no real CSS engine, so this works for inline styles only; visual contrast belongs in Playwright)\n- Missing alt text on images\n- Heading order violations\n\nCross-link: [skills\u002Faccessibility\u002FSKILL.md](..\u002Faccessibility\u002FSKILL.md) for the broader a11y testing playbook.\n\n## When NOT to Use Snapshot Tests\n\nSnapshots of rendered output:\n\n- Break on every styling change\n- Get rubber-stamped during review\n- Test implementation detail (DOM structure), not behavior\n\nAcceptable snapshot uses:\n\n- Pure data serialization functions (`formatInvoice(invoice)` -> stable string)\n- Generated config files (e.g., webpack config output)\n\nFor visual regression on components, use Playwright\u002FCypress screenshots or Percy\u002FChromatic — actual visual diffs, not DOM strings.\n\n## When to Reach for Playwright \u002F Cypress\n\nJSDOM (used by Vitest\u002FJest) cannot:\n\n- Render real layout (flexbox, grid, viewport queries)\n- Run native browser animation, CSS transitions\n- Test scrolling behavior, drag-and-drop, paste from clipboard\n- Handle iframes, popups, downloads, cross-origin flows\n- Run real network in a controlled environment with full DevTools support\n\nFor any of those, use Playwright Component Testing (component test in real browser) or full E2E. See [e2e-testing skill](..\u002Fe2e-testing\u002FSKILL.md).\n\nDecision boundary:\n\n- A hook, a presentational component, a form with logic -> RTL\n- A component whose layout matters or that uses browser APIs not in JSDOM -> Playwright CT\n- A full user flow across multiple pages -> Playwright\u002FCypress E2E\n\n## Coverage Targets\n\n| Layer | Target |\n|---|---|\n| Pure utilities | >=90% |\n| Custom hooks | >=85% |\n| Presentational components | >=80% — behavior, not lines |\n| Container components | >=70% — golden paths + error states |\n| Pages | E2E covered separately; smoke test minimum |\n\nConfigure via `vitest.config.ts` \u002F `jest.config.js`:\n\n```ts\n\u002F\u002F 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```\n\n## Anti-Patterns\n\n- `container.querySelector(\"...\")` — bypasses accessibility queries, lets tests pass when real users would fail\n- Asserting on number of renders — implementation detail\n- `jest.mock(\"react\", ...)` — never mock React. Refactor the component instead\n- Mocking child components by default — tests the integration, not isolation. Mock only when the child has heavy side effects\n- Ignoring `act()` warnings — they signal real bugs (state update after unmount, missing async wrapping)\n- Sharing mutable state across tests — flakes when test order changes\n- Tests that pass with `it.skip()` removed — your test does not actually assert what you think\n\n## TDD Workflow\n\n```\nRED     -> Write failing test for the next requirement\nGREEN   -> Write minimal component code to pass\nREFACTOR -> Improve the component, tests stay green\nREPEAT  -> Next requirement\n```\n\nFor new components:\n\n1. Define the component's prop type and signature\n2. Write the first test for the simplest case\n3. Verify it fails for the right reason\n4. Implement just enough to pass\n5. Add the next test case\n6. Refactor when the third similar test reveals a pattern\n\n## Test Commands\n\n```bash\n# Vitest\nvitest                            # watch\nvitest run                        # one-shot\nvitest run --coverage             # with coverage\nvitest run path\u002Fto\u002Ffile.test.tsx  # single file\n\n# Jest\njest --watch\njest --coverage\njest path\u002Fto\u002Ffile.test.tsx\n\n# CI mode\nCI=true vitest run --coverage\n```\n\n## Related\n\n- Rules: [rules\u002Freact\u002Ftesting.md](..\u002F..\u002Frules\u002Freact\u002Ftesting.md)\n- Skills: [react-patterns](..\u002Freact-patterns\u002FSKILL.md), [accessibility](..\u002Faccessibility\u002FSKILL.md), [e2e-testing](..\u002Fe2e-testing\u002FSKILL.md), [tdd-workflow](..\u002Ftdd-workflow\u002FSKILL.md)\n- Agents: `react-reviewer` (reviews test quality during code review), `tdd-guide` (enforces TDD process)\n- Commands: `\u002Freact-test`, `\u002Freact-review`\n\n## Examples\n\n### Form submission with MSW and userEvent\n\n```tsx\ntest(\"submits user form and shows success\", async () => {\n  server.use(\n    http.post(\"\u002Fapi\u002Fusers\", () =>\n      HttpResponse.json({ id: \"1\", name: \"Alice\" }, { status: 201 }),\n    ),\n  );\n\n  const user = userEvent.setup();\n  renderWithProviders(\u003CUserForm \u002F>);\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: \u002Fsave\u002Fi }));\n\n  expect(await screen.findByText(\u002Fsaved successfully\u002Fi)).toBeInTheDocument();\n});\n```\n\n### Testing an error boundary\n\n```tsx\nfunction Broken() {\n  throw new Error(\"boom\");\n}\n\ntest(\"error boundary renders fallback\", () => {\n  \u002F\u002F Suppress React's console.error noise for the expected throw, then restore so\n  \u002F\u002F the spy does not leak across tests and hide real errors elsewhere.\n  const errorSpy = vi.spyOn(console, \"error\").mockImplementation(() => {});\n  try {\n    render(\n      \u003CErrorBoundary fallback={\u003Cdiv>Something went wrong\u003C\u002Fdiv>}>\n        \u003CBroken \u002F>\n      \u003C\u002FErrorBoundary>,\n    );\n\n    expect(screen.getByText(\"Something went wrong\")).toBeInTheDocument();\n  } finally {\n    errorSpy.mockRestore();\n  }\n});\n```\n\n### Testing a Suspense boundary\n\n```tsx\ntest(\"shows loading then content\", async () => {\n  renderWithProviders(\n    \u003CSuspense fallback={\u003Cdiv>Loading...\u003C\u002Fdiv>}>\n      \u003CUserDetail id=\"1\" \u002F>\n    \u003C\u002FSuspense>,\n  );\n\n  expect(screen.getByText(\"Loading...\")).toBeInTheDocument();\n  expect(await screen.findByText(\"Alice\")).toBeInTheDocument();\n});\n```\n","# React Testing\n\nComprehensive React testing patterns for behavior-focused component tests, custom hook tests, accessibility assertions, and network-level mocking.\n\n## When to Activate\n\n- Writing tests for React components, custom hooks, or pages\n- Adding test coverage to legacy untested components\n- Migrating from Enzyme or class-component-era patterns to React Testing Library\n- Setting up Vitest or Jest for a new React project\n- Mocking HTTP requests in tests\n- Asserting accessibility violations\n- Deciding which tests belong in RTL vs Playwright Component Testing vs full E2E\n\n## Core Principle\n\nTest what the user sees and does, not implementation details.\n\nA test should:\n\n- Render the component with the same providers it has in production\n- Interact with it via accessible queries (role, label) and `userEvent`\n- Assert visible output and observable side effects (callback fired, request sent)\n\nA test should NOT:\n\n- Inspect component state, props passed to children, or which hooks were called\n- Mock React itself or framework hooks\n- Assert on the number of renders or DOM structure beyond what affects users\n\n## Library Choice\n\n| Runner | When | Note |\n|---|---|---|\n| **Vitest** | Vite, Remix, modern setups | Faster, native ESM, Jest-compatible API |\n| **Jest** | Next.js, CRA, established repos | Default for many React projects |\n| **Playwright Component Testing** | Real browser engine needed | Use when JSDOM lacks the required feature |\n| **Cypress Component Testing** | Real browser, Cypress already in use | Alternative to Playwright CT |\n\nPick one. Do not run RTL + Vitest AND Playwright CT in the same repo unless you have a clear lane separation.\n\n## Query Priority\n\nReact Testing Library exposes queries in three tiers — use top-down:\n\n1. **Accessible to everyone**: `getByRole`, `getByLabelText`, `getByPlaceholderText`, `getByText`, `getByDisplayValue`\n2. **Semantic**: `getByAltText`, `getByTitle`\n3. **Test IDs (escape hatch)**: `getByTestId`\n\n```tsx\n\u002F\u002F Best\nscreen.getByRole(\"button\", { name: \u002Fsave\u002Fi });\n\n\u002F\u002F OK for inputs\nscreen.getByLabelText(\"Email\");\n\n\u002F\u002F Last resort\nscreen.getByTestId(\"save-btn\");\n```\n\nVariants:\n\n- `getBy*` — throws if no match\n- `queryBy*` — returns `null` (use for \"assert absence\")\n- `findBy*` — async, returns a Promise (use for elements that appear after async work)\n\n## User Interaction with `userEvent`\n\n```tsx\nimport userEvent from \"@testing-library\u002Fuser-event\";\n\ntest(\"submits the form\", async () => {\n  const user = userEvent.setup();\n  const onSubmit = vi.fn();\n  render(\u003CUserForm onSubmit={onSubmit} \u002F>);\n\n  await user.type(screen.getByLabelText(\"Email\"), \"user@example.com\");\n  await user.click(screen.getByRole(\"button\", { name: \u002Fsave\u002Fi }));\n\n  expect(onSubmit).toHaveBeenCalledWith({ email: \"user@example.com\" });\n});\n```\n\n- Always `await` userEvent calls\n- Call `userEvent.setup()` once per test, reuse the returned `user`\n- `userEvent` simulates a real browser sequence; `fireEvent` dispatches a single synthetic event — prefer `userEvent`\n\n## Async Patterns\n\n```tsx\n\u002F\u002F Element that appears after async work\nexpect(await screen.findByText(\"Loaded\")).toBeInTheDocument();\n\n\u002F\u002F Side effect assertion\nawait waitFor(() => expect(saveSpy).toHaveBeenCalled());\n\n\u002F\u002F Element that should disappear\nawait waitForElementToBeRemoved(() => screen.queryByText(\"Loading\"));\n```\n\nNever `setTimeout` + assertion — flaky. Use the matchers above.\n\n## Network Mocking with MSW\n\nMock Service Worker mocks at the network layer. The component, hooks, and fetch library all behave exactly as in production.\n\n### Setup\n\n```ts\n\u002F\u002F test\u002Fsetup.ts\nimport { setupServer } from \"msw\u002Fnode\";\nimport { http, HttpResponse } from \"msw\";\n\nexport const handlers = [\n  http.get(\"\u002Fapi\u002Fusers\u002F:id\", ({ params }) =>\n    HttpResponse.json({ id: params.id, name: \"Alice\" }),\n  ),\n  http.post(\"\u002Fapi\u002Fusers\", async ({ request }) => {\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(() => server.listen({ onUnhandledRequest: \"error\" }));\nafterEach(() => server.resetHandlers());\nafterAll(() => server.close());\n```\n\nConfigure `onUnhandledRequest: \"error\"` so any unmocked request fails the test loudly — silent passes are worse than red.\n\n### Per-test override\n\n```tsx\ntest(\"renders error on 500\", async () => {\n  server.use(\n    http.get(\"\u002Fapi\u002Fusers\u002F:id\", () => new HttpResponse(null, { status: 500 })),\n  );\n  render(\u003CUserPage id=\"1\" \u002F>);\n  expect(await screen.findByText(\u002Fsomething went wrong\u002Fi)).toBeInTheDocument();\n});\n```\n\n## Provider Wrapping\n\nWrap providers once in a `test-utils.tsx`:\n\n```tsx\n\u002F\u002F test-utils.tsx\nimport { render, RenderOptions } from \"@testing-library\u002Freact\";\nimport { QueryClient, QueryClientProvider } from \"@tanstack\u002Freact-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    \u003CQueryClientProvider client={queryClient}>\n      \u003CThemeProvider theme={lightTheme}>\n        \u003CMemoryRouter>{ui}\u003C\u002FMemoryRouter>\n      \u003C\u002FThemeProvider>\n    \u003C\u002FQueryClientProvider>,\n    options,\n  );\n}\n\nexport * from \"@testing-library\u002Freact\";\n```\n\nThen `import { renderWithProviders, screen } from \"test-utils\"` in every test file.\n\n## Custom Hook Testing\n\n```tsx\nimport { renderHook, act } from \"@testing-library\u002Freact\";\n\ntest(\"useCounter increments and decrements\", () => {\n  const { result } = renderHook(() => useCounter(0));\n\n  expect(result.current.count).toBe(0);\n\n  act(() => result.current.increment());\n  expect(result.current.count).toBe(1);\n\n  act(() => result.current.decrement());\n  expect(result.current.count).toBe(0);\n});\n\ntest(\"useCounter accepts initial value\", () => {\n  const { result } = renderHook(() => useCounter(10));\n  expect(result.current.count).toBe(10);\n});\n\ntest(\"useUser fetches user data\", async () => {\n  \u002F\u002F Instantiate QueryClient ONCE per test outside the wrapper so it survives re-renders.\n  \u002F\u002F 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 }) => (\n    \u003CQueryClientProvider client={queryClient}>{children}\u003C\u002FQueryClientProvider>\n  );\n\n  const { result } = renderHook(() => useUser(\"1\"), { wrapper });\n\n  await waitFor(() => expect(result.current.isSuccess).toBe(true));\n  expect(result.current.data).toEqual({ id: \"1\", name: \"Alice\" });\n});\n```\n\n- Wrap state-changing calls in `act`\n- Test through the hook's public API only\n- For hooks that use context, pass a `wrapper`\n\n## Accessibility Assertions\n\n```tsx\nimport { axe, toHaveNoViolations } from \"jest-axe\"; \u002F\u002F or vitest-axe\nexpect.extend(toHaveNoViolations);\n\ntest(\"UserCard has no a11y violations\", async () => {\n  const { container } = render(\u003CUserCard user={mockUser} \u002F>);\n  expect(await axe(container)).toHaveNoViolations();\n});\n```\n\nRun axe in component tests for every interactive component. Catches:\n\n- Missing labels on form inputs\n- Invalid ARIA usage\n- Poor color contrast (limited — JSDOM has no real CSS engine, so this works for inline styles only; visual contrast belongs in Playwright)\n- Missing alt text on images\n- Heading order violations\n\nCross-link: [skills\u002Faccessibility\u002FSKILL.md](..\u002Faccessibility\u002FSKILL.md) for the broader a11y testing playbook.\n\n## When NOT to Use Snapshot Tests\n\nSnapshots of rendered output:\n\n- Break on every styling change\n- Get rubber-stamped during review\n- Test implementation detail (DOM structure), not behavior\n\nAcceptable snapshot uses:\n\n- Pure data serialization functions (`formatInvoice(invoice)` -> stable string)\n- Generated config files (e.g., webpack config output)\n\nFor visual regression on components, use Playwright\u002FCypress screenshots or Percy\u002FChromatic — actual visual diffs, not DOM strings.\n\n## When to Reach for Playwright \u002F Cypress\n\nJSDOM (used by Vitest\u002FJest) cannot:\n\n- Render real layout (flexbox, grid, viewport queries)\n- Run native browser animation, CSS transitions\n- Test scrolling behavior, drag-and-drop, paste from clipboard\n- Handle iframes, popups, downloads, cross-origin flows\n- Run real network in a controlled environment with full DevTools support\n\nFor any of those, use Playwright Component Testing (component test in real browser) or full E2E. See [e2e-testing skill](..\u002Fe2e-testing\u002FSKILL.md).\n\nDecision boundary:\n\n- A hook, a presentational component, a form with logic -> RTL\n- A component whose layout matters or that uses browser APIs not in JSDOM -> Playwright CT\n- A full user flow across multiple pages -> Playwright\u002FCypress E2E\n\n## Coverage Targets\n\n| Layer | Target |\n|---|---|\n| Pure utilities | >=90% |\n| Custom hooks | >=85% |\n| Presentational components | >=80% — behavior, not lines |\n| Container components | >=70% — golden paths + error states |\n| Pages | E2E covered separately; smoke test minimum |\n\nConfigure via `vitest.config.ts` \u002F `jest.config.js`:\n\n```ts\n\u002F\u002F 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```\n\n## Anti-Patterns\n\n- `container.querySelector(\"...\")` — bypasses accessibility queries, lets tests pass when real users would fail\n- Asserting on number of renders — implementation detail\n- `jest.mock(\"react\", ...)` — never mock React. Refactor the component instead\n- Mocking child components by default — tests the integration, not isolation. Mock only when the child has heavy side effects\n- Ignoring `act()` warnings — they signal real bugs (state update after unmount, missing async wrapping)\n- Sharing mutable state across tests — flakes when test order changes\n- Tests that pass with `it.skip()` removed — your test does not actually assert what you think\n\n## TDD Workflow\n\n```\nRED     -> Write failing test for the next requirement\nGREEN   -> Write minimal component code to pass\nREFACTOR -> Improve the component, tests stay green\nREPEAT  -> Next requirement\n```\n\nFor new components:\n\n1. Define the component's prop type and signature\n2. Write the first test for the simplest case\n3. Verify it fails for the right reason\n4. Implement just enough to pass\n5. Add the next test case\n6. Refactor when the third similar test reveals a pattern\n\n## Test Commands\n\n```bash\n# Vitest\nvitest                            # watch\nvitest run                        # one-shot\nvitest run --coverage             # with coverage\nvitest run path\u002Fto\u002Ffile.test.tsx  # single file\n\n# Jest\njest --watch\njest --coverage\njest path\u002Fto\u002Ffile.test.tsx\n\n# CI mode\nCI=true vitest run --coverage\n```\n\n## Related\n\n- Rules: [rules\u002Freact\u002Ftesting.md](..\u002F..\u002Frules\u002Freact\u002Ftesting.md)\n- Skills: [react-patterns](..\u002Freact-patterns\u002FSKILL.md), [accessibility](..\u002Faccessibility\u002FSKILL.md), [e2e-testing](..\u002Fe2e-testing\u002FSKILL.md), [tdd-workflow](..\u002Ftdd-workflow\u002FSKILL.md)\n- Agents: `react-reviewer` (reviews test quality during code review), `tdd-guide` (enforces TDD process)\n- Commands: `\u002Freact-test`, `\u002Freact-review`\n\n## Examples\n\n### Form submission with MSW and userEvent\n\n```tsx\ntest(\"submits user form and shows success\", async () => {\n  server.use(\n    http.post(\"\u002Fapi\u002Fusers\", () =>\n      HttpResponse.json({ id: \"1\", name: \"Alice\" }, { status: 201 }),\n    ),\n  );\n\n  const user = userEvent.setup();\n  renderWithProviders(\u003CUserForm \u002F>);\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: \u002Fsave\u002Fi }));\n\n  expect(await screen.findByText(\u002Fsaved successfully\u002Fi)).toBeInTheDocument();\n});\n```\n\n### Testing an error boundary\n\n```tsx\nfunction Broken() {\n  throw new Error(\"boom\");\n}\n\ntest(\"error boundary renders fallback\", () => {\n  \u002F\u002F Suppress React's console.error noise for the expected throw, then restore so\n  \u002F\u002F the spy does not leak across tests and hide real errors elsewhere.\n  const errorSpy = vi.spyOn(console, \"error\").mockImplementation(() => {});\n  try {\n    render(\n      \u003CErrorBoundary fallback={\u003Cdiv>Something went wrong\u003C\u002Fdiv>}>\n        \u003CBroken \u002F>\n      \u003C\u002FErrorBoundary>,\n    );\n\n    expect(screen.getByText(\"Something went wrong\")).toBeInTheDocument();\n  } finally {\n    errorSpy.mockRestore();\n  }\n});\n```\n\n### Testing a Suspense boundary\n\n```tsx\ntest(\"shows loading then content\", async () => {\n  renderWithProviders(\n    \u003CSuspense fallback={\u003Cdiv>Loading...\u003C\u002Fdiv>}>\n      \u003CUserDetail id=\"1\" \u002F>\n    \u003C\u002FSuspense>,\n  );\n\n  expect(screen.getByText(\"Loading...\")).toBeInTheDocument();\n  expect(await screen.findByText(\"Alice\")).toBeInTheDocument();\n});\n```\n",{"name":5,"metadata":55,"description":7},{"origin":56},"ECC","main","74715deacdc69119d739f38916f8ee4f0f979ebf","skills\u002Fstorage\u002Faffaan-m_ECC\u002Freact-testing",0,"https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills","https:\u002F\u002Fgithub.com\u002Fmdnaimul22","AI Agents Workflows Automation | Specializing in Python, FastAPI, MCP Agents & Custom ERP.","2026-11-11 21:16:57",{"source":8,"skillName":5,"commands":66,"prompt":76,"zipAvailable":77},[67,70,73],{"tool":68,"command":69},"npx","npx skills add mdnaimul22\u002Fhuman-skills --skill react-testing",{"tool":71,"command":72},"bunx","bunx skills add mdnaimul22\u002Fhuman-skills --skill react-testing",{"tool":74,"command":75},"pnpm","pnpm dlx skills add mdnaimul22\u002Fhuman-skills --skill react-testing","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Freact-testing\u002FSKILL.md",true,[],[80,88,96,103,110,117],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":87},"01M767791C1KRP2ZRW2Z73VZ5Q","system-lifecycle-designer","Universal architectural methodology for designing granular, atomic, and sub-atomic lifecycles and end-to-end workflows for single functionality integrations across any domain (daemons, batch jobs, request transactions, resource pools). Provides patterns for deterministic identity, pre-commit validation, differential reconciliation, sticky leasing, state machines, transactional persistence, and closed-loop feedback.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fmy_skills\u002Fsystem-lifecycle-designer\u002FSKILL.md",[],[],"2026-11-12 13:55:43",{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":95},"01M748ABPN5F1FANHH6HKZQMXT","style-sampling","Make a new episode in a proven video style - Collage Explainer, Finance Explainer, Animated Science Explainer, 3D Brand Explainer, 3D True Crime - on the person's topic. Use for \"an episode of\", \"in the style of\", \"sample this style\", 「用这个风格做一集」. One video to copy is reverse-any-video.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fheygen-com_hyperframes\u002Fstyle-sampling\u002FSKILL.md",[],[],"2026-11-11 15:11:14",{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":95},"01M748A59V04PKW4HA0XQ81FGP","reverse-any-video","Rebuild any video file as an editable HyperFrames project - motion graphics, talking heads, live action or AI-generated footage - checked against the original frame by frame. Use to reverse, recreate, remake, replicate or copy a video, or 「复刻这个视频」「照着这个视频做一个」.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fheygen-com_hyperframes\u002Freverse-any-video\u002FSKILL.md",[],[],{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":95},"01M7487T50P55CSXMWXZ0G9KRG","typescript-patterns","TypeScript patterns for strict, type-safe, maintainable code in modern TypeScript and JavaScript applications. Covers strict compiler configuration, type design, narrowing, discriminated unions, generics, async and error handling, module boundaries, dependency hygiene, and type-level testing. Use when writing or reviewing TypeScript or JavaScript code.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Ftypescript-patterns\u002FSKILL.md",[],[],{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":95},"01M7487ERZRGPC5NJ75077Y238","test-collaboration","Inventory and govern a project's test assets. Connect requirements, business rules, risks, bugs, and cross-boundary contracts to stable TEST-IDs and executable evidence in the repository's existing test registry or TESTS.md. Use for test inventory, test gap analysis, unit\u002Fintegration\u002Fcontract\u002FE2E\u002Fsmoke classification, bug-to-test regression protection, consumer\u002Fprovider contract testing, test-necessity review, and pre-delivery evidence review.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Ftest-collaboration\u002FSKILL.md",[],[],{"skillNo":118,"name":119,"nameZh":6,"description":120,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":121,"categories":122,"keywords":123,"publishedAt":95},"01M748721J3GKR2WS6K0QWFC35","story-lifecycle","Manage a file-based epic → story → sprint development loop without requiring an external project management tool. Creates and tracks epics, breaks them into user stories, assigns them to sprints, and drives implementation story by story. Use when starting a new feature initiative or when the team has no Jira\u002FLinear\u002FTaiga but needs structured delivery tracking.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Fstory-lifecycle\u002FSKILL.md",[],[]]