React Testing Library
6 min read Quiz at the end
React Testing Library tests from the user's perspective. Use screen.getByRole(), screen.getByLabelText(), and userEvent to interact with the UI. Test what users see and do, not internal component state.
Testing with React Testing Library npm install @testing-library/react @testing-library/jest-dom
import { render, screen, fireEvent } from "@testing-library/react";
test("counter increments", () => {
render( );
const btn = screen.getByText("+");
const count = screen.getByText("Count: 0");
fireEvent.click(btn);
expect(screen.getByText("Count: 1")).toBeInTheDocument();
});
Topic Quiz · 5 questions
Test your understanding before moving on
1. What does RTL encourage testing?
A. Implementation details
B. Component internals
C. User-visible behaviour
D. DOM structure
💡 RTL encourages testing what the user sees and does, not implementation details.
2. Which function renders a component in tests?
A. mount()
B. shallow()
C. render()
D. create()
💡 render(<Component />) from RTL renders into a test DOM.
3. How do you find an element by text?
A. screen.findText()
B. screen.getByText()
C. document.findByText()
D. querySelector()
💡 screen.getByText('text') finds an element by its visible text content.
4. What does fireEvent.click() do?
A. Checks click handler
B. Simulates a click on an element
C. Opens a modal
D. Triggers CSS
💡 fireEvent.click(element) simulates a user click on the element.
5. What is the user-event library for?
A. Server testing
B. More realistic user interaction simulation
C. Style testing
D. Snapshot testing
💡 @testing-library/user-event simulates real browser events (typing, clicking) more accurately than fireEvent.
Submit answers