accelint-react-testing
Use when writing, reviewing, or refactoring React component tests with Testing Library. Load when you see render(), screen, fireEvent, userEvent, waitFor, or *.test.tsx files. Covers query priority (getByRole > getByLabelText > getByText), user-centric testing patterns, async utilities, custom renders with providers, and accessibility-first assertions. Keywords include RTL, Testing Library, screen, getByRole, findBy, queryBy, userEvent, waitFor, toBeInTheDocument, testing-library/react, testing-library/user-event, jest-dom.
What this skill does
# React Testing Best Practices
Expert guidance for writing maintainable, user-centric React component tests with Testing Library. Focused on query selection, accessibility-first testing, and avoiding implementation details.
## NEVER Do When Writing React Tests
- **NEVER query by test IDs before trying accessible queries** - Test IDs bypass accessibility verification: a button with `data-testid="submit"` but no accessible name works in tests but fails for screen reader users. When tests pass with test IDs, you ship inaccessible UIs. Query hierarchy: `getByRole` > `getByLabelText` > `getByText` > `getByTestId`. Each step down this list means less confidence your UI is usable.
- **NEVER use `fireEvent` for user interactions when `userEvent` is available** - `fireEvent` dispatches single DOM events, missing the event sequence real users trigger: `fireEvent.click()` fires one click event, but real users trigger focus → mousedown → mouseup → click. Components that work with fireEvent break in production when users interact normally. `userEvent.click()` simulates the full interaction sequence, catching bugs fireEvent misses.
- **NEVER test implementation details instead of user behavior** - Tests that verify "state variable X equals Y" or "function Z was called" create false failures: you refactor from useState to useReducer, all tests fail, yet the UI works identically. Testing implementation details punishes refactoring and provides zero confidence the user experience works. Test what users see and do (rendered output, interaction results), not how your component achieves it internally.
- **NEVER query from `container` or use destructured queries after initial render** - `const { getByText } = render(<Component />)` creates stale queries that miss updates: after state changes, destructured queries search the initial DOM snapshot, missing newly rendered elements. This causes "element not found" errors for elements that are actually present. Always use `screen.getByText()` which automatically queries the current DOM state. Using screen consistently also makes tests more maintainable - adding a new query doesn't require updating the destructuring.
- **NEVER add aria-label or role attributes solely for tests** - If you're adding `aria-label="submit-button"` or `role="button"` just so tests can find elements, you're working backwards. Tests should verify the component is already accessible, not make it accessible for tests. Adding test-only ARIA pollutes production code and masks real accessibility problems. Fix the component's semantic HTML and existing ARIA first.
- **NEVER snapshot entire component trees without specific assertions** - Massive snapshots with 500+ lines break on any change (updated classname, new prop, reordered elements), forcing reviewers to approve diffs they can't meaningfully evaluate. When test failures require "just update the snapshot" without understanding why, the test has zero value. Snapshot specific critical structures (error messages, data tables) with targeted assertions for everything else.
- **NEVER use `waitFor` for actions that return promises** - `waitFor(() => expect(element).toBeInTheDocument())` polls repeatedly until timeout when a promise-based `findBy` query solves it in one shot: `await screen.findByText('loaded')` waits for the element to appear without polling. Reserve waitFor for assertions that can't use findBy (checking element disappears, waiting for attribute changes).
- **NEVER perform side effects inside waitFor callback** - `waitFor(() => { fireEvent.click(button); expect(text).toBeInTheDocument(); })` runs the click multiple times as waitFor retries, causing unpredictable behavior. waitFor is for waiting on assertions, not triggering actions. Perform all actions outside waitFor, then use waitFor only for the assertion: `fireEvent.click(button); await waitFor(() => expect(text).toBeInTheDocument());` or better yet, `await userEvent.click(button); expect(await screen.findByText(text)).toBeInTheDocument();`.
- **NEVER create custom renders without documenting provider requirements** - A custom `renderWithRedux` function with undocumented required store shape breaks for every developer: they call `render(<Component />)` instead of `renderWithRedux()`, tests fail with cryptic "Cannot read property of undefined", wasting 15 minutes debugging. Centralize provider setup in test utils with TypeScript types that enforce correct usage, or document required wrappers prominently.
- **NEVER mix queries from different Testing Library imports** - Importing both `@testing-library/react` render and `@testing-library/dom` queries creates confusion: `screen` from react package doesn't work with `getByRole` from dom package, causing "screen.getByRole is not a function" errors. Import all queries from `@testing-library/react` for React components - it re-exports everything from dom with React-specific enhancements.
## Before Writing Tests, Ask
Apply these thinking patterns before implementing React component tests:
### Query Selection Strategy
- **Which query matches how users find this element?** Real users don't look for test IDs or CSS classes - they look for labels, buttons, headings. If you can't query by role or label, your UI lacks accessibility. Query difficulty reveals UX problems before they reach production.
- **Does this element need to be found at all?** Not every element needs a query assertion. Users don't verify "loading spinner exists" - they verify "data appears after loading". Test outcomes, not intermediate states.
- **Should I use getBy, queryBy, or findBy?** Start with getBy for immediate presence - it gives the best error messages. Use queryBy only when asserting absence (.not.toBeInTheDocument()). Use findBy for async appearance. Never use queryBy + expect(...).toBeInTheDocument() - use getBy instead for better error messages when the element is missing.
### User vs Implementation Testing
- **What would a user do to verify this works?** Users click buttons and read text - they don't check state variables or mock function calls. If your test uses `rerender()` or accesses component internals, you're testing implementation. Refactor to test through user actions.
- **Will this test survive a refactoring that doesn't change behavior?** If renaming a function or switching from useState to useReducer breaks the test, you're testing implementation details. These tests waste time blocking safe changes while providing no confidence the UI actually works.
### Async and Timing
- **Is this query for something that loads asynchronously?** Use `findBy*` for anything loaded via useEffect, API calls, or setTimeout. `getBy*` throws immediately if element is missing; `findBy*` waits for it to appear. Using getBy for async content creates race conditions that only fail in CI.
- **Am I waiting for an element to appear or disappear?** Appearance = `findBy*` query. Disappearance = `waitForElementToBeRemoved`. State changes = `waitFor` with assertion. Each has different semantics; using the wrong one causes flaky tests or longer timeouts.
### Test Isolation and Setup
- **Does this component need context providers to render?** Components using useContext, Redux hooks, or React Router throw without providers. Create custom render utilities that wrap components in required providers automatically. Repeating provider setup in every test file is a maintenance disaster.
- **What's the minimal setup needed for this test case?** Tests with excessive setup (mocking 10 functions for a button test) are fragile and slow. Mock only external dependencies (APIs, localStorage), never your own functions. If setup is complex, the component design might be the problem.
## How to Use
This skill uses **progressive disclosure** to minimize context usage:
### 1. Start with the Overview (AGENTS.md)
Read [AGENTS.md](AGENTS.md) for a concise overview of all rules with one-line summaries.
### 2. Load Specific Rules as Needed
Use these eRelated in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.