Test interactions by role and name
Test the interface as a visitor experiences it
React Testing Library renders components into a test DOM and helps locate elements by their meaning. user-event models common interactions and associated events. Prefer a button with its accessible name over a CSS class or an internal Hook value. A test should still pass after a safe refactor that preserves behavior. The following component imports the previously tested reservation rule. Its button is disabled when stock is gone and the live status reports the reserved count. Native buttons support keyboard activation without a custom key handler.
import React, { useState } from 'react';import { reserve } from './reservation.mjs';export default function ReservePanel() { const [state, setState] = useState({ available: 2, reserved: 0 }); return <section aria-label="Seed reservation"> <p>Available: {state.available}</p> <button type="button" disabled={state.available === 0} onClick={() => setState(s => reserve(s, 1))}>Reserve one packet</button> <p role="status">Reserved: {state.reserved}</p> </section>;}Two activations reserve both packets. The third is prevented by the disabled control and the rule also rejects over-reservation. In a real app a server response determines whether stock was reserved. The component test should check the visible count, disabled state and the ability to activate the control via keyboard. A status region exists before updates; a DOM assertion alone does not establish that a screen reader announced it.
Use role queries and await interactions
import React from 'react';import { afterEach, expect, test } from 'vitest';import { cleanup, render, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';import '@testing-library/jest-dom/vitest';import ReservePanel from './ReservePanel.jsx';afterEach(cleanup);test('keyboard and click reserve until stock is exhausted', async () => { const user = userEvent.setup(); render(<ReservePanel />); const button = screen.getByRole('button', { name: 'Reserve one packet' }); await user.tab(); expect(button).toHaveFocus(); await user.keyboard('{Enter}'); expect(screen.getByRole('status')).toHaveTextContent('Reserved: 1'); await user.click(button); expect(screen.getByText('Available: 0')).toBeInTheDocument(); expect(button).toBeDisabled(); await user.click(button); expect(screen.getByRole('status')).toHaveTextContent('Reserved: 2');});getByRole requires exactly one match now and throws otherwise. queryByRole returns null for no match, useful for asserting absence, but still throws for multiple matches. findByRole returns a Promise and retries until a match or timeout. Use the appropriate query rather than putting every assertion inside a retry. screen queries the document body; within scopes a query to a particular region. Prefer roles and names, then labels or visible text, and use test IDs when no meaningful semantic selector exists. Avoid checking the exact HTML string or counting every render. user-event calls are asynchronous; await them.
Separate DOM setup from the test contract
import { defineConfig } from 'vitest/config';export default defineConfig({ test: { environment: 'jsdom', include: ['**/*.vitest.test.mjs', '**/*.test.jsx'] }});This is a minimal configuration for the staged examples, which explicitly import React. Use approved matching React/React DOM, Vitest, jsdom, Testing Library React and DOM, user-event v14 and jest-dom packages. Run vitest run with the reviewed local executable. Explicit cleanup unmounts each rendered tree. React act flushes work relevant to a test before assertions; Testing Library handles common render and interaction wrappers. For externally resolved promises use awaited act from React where needed. Do not import act from react-dom/test-utils for new React 19 tests. react-test-renderer is deprecated; migrate behavior checks rather than copying old shallow-render assumptions. jsdom is not a real layout engine; geometry, media queries, native focus nuances and real assistive technology need browser tests. StrictMode can intentionally repeat setup/cleanup in development, so test the effect contract rather than a universal exact count.