Manual clicking can miss a button or an unlikely sequence of events, and every change demands another pass. Automated tests make those checks repeatable: they simulate interactions and verify that the application behaves as intended. Component tests are especially useful for catching regressions as a React application changes. section 10.0 section 10.4
Use Vitest to run tests and React Testing Library to inspect components as a user encounters them. Vitest fits Vite projects; Jest is another common runner with an almost identical API. These tools have different jobs, and neither runner requires React Testing Library. Test files run when requested and are excluded from the production bundle. section 10.0 section 10.1
Write a component test around its observable responsibility:
- State what the component must do before choosing assertions. For a navigation item, that means a list item containing a link whose destination, title, and text match its props. section 10.1
- Arrange the rendered component, act when interaction is required, and assert the result. Find elements by roles such as `listitem`, `link`, `spinbutton`, and `button`, using accessible names to distinguish controls. section 10.1 section 10.2.3 section 10.4
- For interaction, use `userEvent`: typing into a number input triggers the associated focus, input, and change events. Mock a callback when the behavior to verify is its invocation. section 10.2.3
Listing 10.1 Unit-testing MenuItem
import { #1
render, #1
screen, #1
getByRole, #1
} from "@testing-library/react"; #1
import "@testing-library/jest-dom"; #2
import MenuItem from "./MenuItem"; #3
test( #4
"MenuItem renders a link in a list item", #4
() => { #4
// ARRANGE
render(<MenuItem href="/blog" label="Blog" />); #5
// ASSERT
const listItem = screen.getByRole("listitem"); #6
const link = getByRole(listItem, "link"); #6
expect(link).toHaveAttribute("href", "/blog"); #7
expect(link).toHaveAttribute("title", "Blog"); #7
expect(link).toHaveTextContent("Blog"); #7
});
A complete static-component test renders a navigation item, locates its link within a list item, and checks the link’s attributes and text. section 10.1
Testing a timer form
Render the add-timer form with a mocked `onAdd` callback. Find the minutes and seconds fields by their `spinbutton` role and names, type values, click the Start button, and check the callback. The example does not handle invalid input or a submitted zero time, so those behaviors are not claimed as tested. section 10.2.3
External or complex internal dependencies can make a component difficult to isolate. Mock browser APIs, modules, libraries, or context when that helps focus the test. Choose what to test from the behavior the component actually promises, rather than treating every possible assertion as equally useful. section 10.4 section 10.1




















































