0
0
ReactHow-ToBeginner · 4 min read

How to Use screen in Testing Library in React

In React Testing Library, use the screen object to access queries like getByText or getByRole for selecting elements in your rendered component. It provides a simple, global way to find elements without destructuring queries from the render result.
📐

Syntax

The screen object is imported from @testing-library/react and provides access to all query methods globally after rendering a component.

Common queries include screen.getByText(), screen.getByRole(), and screen.queryByTestId().

This avoids the need to destructure queries from the render function's return value.

javascript
import { render, screen } from '@testing-library/react';

render(<MyComponent />);
const element = screen.getByText('Hello');
💻

Example

This example shows how to render a simple component and use screen to find a button by its role and text, then check if it is in the document.

javascript
import React from 'react';
import { render, screen } from '@testing-library/react';

function Greeting() {
  return <button>Click me</button>;
}

test('finds button using screen', () => {
  render(<Greeting />);
  const button = screen.getByRole('button', { name: /click me/i });
  expect(button).toBeInTheDocument();
});
Output
Test passes with no errors
⚠️

Common Pitfalls

  • Not importing screen from @testing-library/react causes errors.
  • Using queries on the render result instead of screen can make tests less readable.
  • Using getBy* queries without handling errors can cause tests to fail if elements are missing; consider queryBy* for optional elements.
javascript
/* Wrong way: destructuring queries from render result */
import { render } from '@testing-library/react';

const { getByText } = render(<MyComponent />);
const element = getByText('Hello');

/* Right way: use screen globally */
import { render, screen } from '@testing-library/react';

render(<MyComponent />);
const element = screen.getByText('Hello');
📊

Quick Reference

screen Query MethodDescription
getByText(text)Finds element by exact or partial text, throws if not found
queryByText(text)Finds element by text, returns null if not found
getByRole(role, options)Finds element by ARIA role and accessible name
queryByTestId(id)Finds element by data-testid attribute, returns null if not found
findByText(text)Async query that waits for element with text to appear

Key Takeaways

Import and use screen from @testing-library/react to access queries globally.
screen improves test readability by avoiding destructuring queries from render results.
Use getBy* queries when elements must exist, and queryBy* when elements may be absent.
Common queries include getByText, getByRole, and queryByTestId.
Always import screen to avoid reference errors in your tests.