React Testing Library - Targeting elements with data-testid

This is a short snippet and/or cheat sheet - for full guides, blog posts and lessons on everything frontend testing related please check out the rest of HowToTestFrontend.com.

A quick example of using data-testid selectors with React Testing Library.

#testing-library#selectors

Why use data-testid?

Use data-testid when accessible selectors (like role or label text) are not available.

Example

First, add the data-testid attribute to your component:

code
// Button.tsx
export function Button() {
  return (
    <button data-testid="submit-button">
      Submit
    </button>
  );
}
code
import {
  render,
  screen,
} from '@testing-library/react';
import { Button } from './Button';

it('finds the button by test id', () => {
  render(<Button />);
  expect(
    screen.getByTestId('submit-button')
  ).toBeInTheDocument();
});

Tips

  • Prefer roles/labels when possible.
  • Keep test IDs stable and descriptive.