Introduction
When writing tests using React Testing Library, I encountered some difficulty locating elements, so I'll organize the necessary points here.
1. getByText
screen.getByText(“Hello”);
Use getByText when searching for elements that match specific text.
It's useful when you know that text “definitely exists” on the screen.
For example, use it when you want to verify simple text like fixed text displayed in headings or buttons.
2. getByRole
screen.getByRole(“button”, { name: /Submit/i });
getByRole is a method for locating elements by specifying their “role” (e.g., button, link, heading).
3. getByLabelText
screen.getByLabelText(“Username”);
getByLabelText is used to find input forms based on their labels.
Summary
Find by text → getByText
Find by role → getByRole
Find forms by label → getByLabelText
Top comments (0)