CodeBlanks Logo Icon CodeBlanks

getByText

Learn to find elements with getByText.

What is getByText?

getByText is a query that finds an element in the rendered tree whose text equals the given value. Calling getByText('Hello') returns the Text component containing 'Hello'. If several match, it throws.

This query is ideal for writing tests based on what the user sees. It focuses on visible text, not on the app's internals. If text changes the test must update; for text that changes often, testID may be preferred. Still, for behavior focused tests getByText is the most natural choice; it is readable and meaningful.

The found element

getByText returns an element; you run expect on it. For example expect(getByText('Hello')).toBeTruthy() says the element exists. expect(getByText('Hello')).toBeDefined() is a similar check.

Sometimes you want to test whether text changed. First find the element with getByText('Old'), do an interaction, then check with getByText('New') that it changed. If not found getByText throws; the test turns red. This exception can be used to test absence: expect(() => getByText('Deleted')).toThrow() confirms the element is gone.

Practice Find an element with getByText

An App component is already defined; it returns <Text>Welcome</Text>. Call render(<App />); find the 'Welcome' text with getByText. Assert with expect(...).toBeTruthy().

Starter code

App.js
// Import render

// Write a test named 'welcome exists'
// render App, find 'Welcome' with getByText, assert with toBeTruthy

Sample solution

App.js
import { render } from "@testing-library/react-native";
import { Text } from "react-native";

function App() {
  return <Text>Welcome</Text>;
}

test("welcome exists", () => {
  const { getByText } = render(<App />);
  expect(getByText("Welcome")).toBeTruthy();
});

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each query to its behavior

Term Meaning
getByText Returns if text found
getByTestId Finds by testID
getAllByText Returns all matches
queryByText Returns null if missing

2 The getByText call

Question
const el = ____('Merhaba');
Answer
const el = getByText('Merhaba');

Explanation: getByText finds the element by text.

3 What does getByText do when text is missing?

App.js
const el = getByText('yok');
  • Throws an error Correct answer
  • Returns undefined
  • Returns null
  • Returns an empty array

Explanation: getByText throws when it cannot find text.

All lessons in Intermediate