0
0
ReactHow-ToBeginner · 4 min read

How to Check if Element Exists in React Test Using Testing Library

In React tests, use screen.queryByText or screen.queryByTestId from React Testing Library to check if an element exists. If the element is found, these functions return the element; if not, they return null. You can then assert its presence or absence using expect(element).toBeInTheDocument() or check for null.
📐

Syntax

Use screen.queryBy* methods to check if an element exists without throwing an error if it does not. The common pattern is:

  • const element = screen.queryByText('text') - finds element by visible text.
  • const element = screen.queryByTestId('id') - finds element by test ID.
  • Check if element is null to know if it exists.
javascript
const element = screen.queryByText('Hello World');
if (element) {
  // element exists
} else {
  // element does not exist
}
💻

Example

This example shows how to test if a button with text 'Click me' exists in the rendered component.

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

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

test('checks if button exists', () => {
  render(<MyButton />);
  const button = screen.queryByText('Click me');
  expect(button).toBeInTheDocument();
});
Output
Test passes if button is found; fails if not.
⚠️

Common Pitfalls

Using getBy* instead of queryBy* to check existence causes errors if element is missing. getBy* throws an error when no element is found, so it is not suitable for existence checks.

Always use queryBy* when you want to check if an element exists or not without failing the test immediately.

javascript
/* Wrong way - throws error if element missing */
const element = screen.getByText('Missing Text'); // throws if not found

/* Right way - returns null if element missing */
const element = screen.queryByText('Missing Text');
if (element === null) {
  // element does not exist
}
📊

Quick Reference

MethodReturnsUse Case
screen.getByText('text')Element or throws errorUse when element must exist
screen.queryByText('text')Element or nullUse to check if element exists
screen.getByTestId('id')Element or throws errorMust exist by test id
screen.queryByTestId('id')Element or nullCheck existence by test id

Key Takeaways

Use screen.queryBy* methods to safely check if an element exists without errors.
screen.getBy* methods throw errors if element is missing, so avoid them for existence checks.
Check if the returned element is null to know if it exists or not.
Use expect(element).toBeInTheDocument() to assert presence in tests.
Use test IDs or visible text with queryBy* for flexible element selection.