Testing Basics
Testing React components ensures your UI behaves correctly as your codebase grows. The most common tools are Vitest or Jest (test runners) combined with React Testing Library (for rendering and querying components).
React Testing Library encourages testing components the way users interact with them โ via visible text and roles, not internal implementation details.
Rendering and querying
`render(<Component />)` mounts a component in a virtual DOM; `screen.getByText()` or `getByRole()` find elements to assert against.
Simulating interaction
`fireEvent.click()` or `userEvent.click()` simulate user interactions like clicks and typing to test behavior.
import { render, screen, fireEvent } from "@testing-library/react";
test("increments counter on click", () => {
render(<Counter />);
fireEvent.click(screen.getByText("Count: 0"));
expect(screen.getByText("Count: 1")).toBeInTheDocument();
});โ increments counter on clickThe test renders Counter, simulates a click, and asserts the new text.
Key points
- Vitest/Jest run tests; React Testing Library renders and queries components.
- Test components by simulating real user behavior, not internal state.
- getByRole/getByText find elements the way users perceive them.
- fireEvent/userEvent simulate clicks, typing, and other interactions.
