Happy DOM Tests
Act as a top-tier software engineer with serious testing skills.
Write React component tests for: $ARGUMENTS
Each test must answer these 5 questions:
- •What is the component under test? (test should be in a named describe block)
- •What is the expected behavior? ($given and $should arguments are adequate)
- •What props or state trigger the behavior? (use a factory function with defaults)
- •What does the user see or interact with? (accessible queries, not implementation details)
- •How can we find the bug? (implicitly answered if the above questions are answered correctly)
Rules
- •Use Vitest with describe, expect, and test. Test files use the
.test.tsxextension. - •Tests must use the "given: ..., should: ..." prose format.
- •Colocate test files next to the component they test.
- •Import
render,screen,userEvent, andcreateRoutesStubfrom a shared~/test/react-test-utilsmodule that wraps Testing Library with app providers (i18n, form context, etc.). - •Create a props factory function per component with sensible defaults. Each test overrides only what it needs.
- •Use
createRoutesStubfrom React Router to provide routing context. PassinitialEntriesfor specific routes. - •Use accessible queries as the primary locator strategy:
screen.getByRole,screen.getByLabel,screen.getByText. - •Use
screen.queryByRole(returns null) for negative assertions — nevergetByRolewithnot.toBeInTheDocument. - •Use regex with case-insensitive flag for text matching:
{ name: /submit/i }. - •Use
userEvent.setup()for user interactions — neverfireEvent. - •Use
vi.fn()for mock callbacks. Usevi.spyOnfor global mocks. - •Use
renderHookandactfor testing custom hooks. Usevi.useFakeTimers()for timer-based hooks. - •Use
@faker-js/fakerandcuid2in factories for realistic test data. - •Use existing infrastructure factories (
*-factories.server.ts) when props come from database entities. - •Wrap
RouterStubin additional providers (e.g.SidebarProvider) when the component requires them. - •Pass
hydrationDatatoRouterStubwhen the component reads loader data. - •Use
test.eachfor parametrized tests when multiple inputs produce similar outcomes. - •Assert accessibility attributes:
toHaveAttribute("aria-selected", "true"),toHaveAttribute("aria-current", "page"). - •Assert element state:
toBeDisabled(),toBeEnabled(),toHaveFocus(). - •Assert structure:
toBeInTheDocument(),toHaveAttribute("href", "/path"),toHaveTextContent(/text/i). - •Capture
actualandexpectedvalues in variables before asserting withtoEqualfor pure logic checks.
When NOT to use this skill
- •For pure function tests without React (
.test.ts), use/unit-testsinstead. - •For database or server action tests (
.spec.ts), use/integration-testsinstead. - •For browser-level user flow tests (
.e2e.ts), use/e2e-testsinstead. - •This skill is for React component and hook render tests (
.test.tsx) only.