CodeBlanks Logo Icon CodeBlanks

render

Learn to render components with render.

What does render return?

render draws a component and returns a result object. This object holds query functions: getByText, getByTestId, getByPlaceholderText and more. The queries find elements in the rendered tree.

Typical usage: const { getByText } = render(<App />). Here getByText is taken from the result object with destructuring. Calling getByText('Hello') returns the element whose text is 'Hello'. If it cannot find it, it throws; this turns the test red. That is why getByText is used for text whose presence is certain.

The render result

The most common queries on the object returned by render are: getByText finds by text, getByTestId by the testID prop, and getByPlaceholderText by placeholder text. Each returns one element; if not found it throws.

You can run assertions like expect(el).toBeTruthy() on the element returned by a query. Sometimes a query can match several elements; in that case getAllByText is used and returns an array. When writing tests pick the most stable query: text can change but testID stays. That is why production prefers testID.

Practice Use a query with render

An App component is already defined; it returns <Text>Hello</Text>. Call render(<App />); take getByText from the result. Find the element with getByText('Hello') and assert with expect(...).toBeTruthy().

Starter code

App.js
// Import render

// Write a test named 'hello exists'
// render App, find 'Hello' 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>Hello</Text>;
}

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

Questions and answers

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

1 Take a query from the render result

Question
const { ____ } = render(<App />);
Answer
const { getByText } = render(<App />);

Explanation: answer: getByText. It is the most common query.

2 Where does render run?

App.js
const { getByText } = render(<App />);
  • In the browser
  • On the device
  • In production
  • In a test environment Correct answer

Explanation: render runs in a JavaScript test environment.

3 Match each query to its role

Term Meaning
getByText Finds by text
getByTestId Finds by testID
getByPlaceholderText Finds by placeholder
getAllByText Finds all matches

All lessons in Intermediate