DEV Community

Kazutora Hattori
Kazutora Hattori

Posted on

A Summary of Element Search Methods in React Testing Library (getByText / getByRole / getByLabelText)

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”);
Enter fullscreen mode Exit fullscreen mode

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 });
Enter fullscreen mode Exit fullscreen mode

getByRole is a method for locating elements by specifying their “role” (e.g., button, link, heading).

3. getByLabelText

screen.getByLabelText(“Username”);
Enter fullscreen mode Exit fullscreen mode

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)