
ReactJS
Learn the best ways to find elements in tests.
1. getByRole - Most semantic (recommended)
2. getByLabelText - For form labels
3. getByPlaceholderText - For placeholder text
4. getByText - For other text
5. getByTestId - Last resort
import { render, screen } from '@testing-library/react';
// Get by role (best practice)
const button = screen.getByRole('button');
// Get by label text
const input = screen.getByLabelText('Email');
// Get by text content
const heading = screen.getByText('Welcome');
// Get multiple elements
const items = screen.getAllByRole('listitem');
// Query (returns null if not found)
const element = screen.queryByRole('button');
// Find (async, waits for element)
const element = await screen.findByRole('button');test('finds button with specific name', () => {
render(<LoginForm />);
const button = screen.getByRole('button', { name: /submit/i });
expect(button).toBeInTheDocument();
});
test('finds multiple elements', () => {
render(<TodoList />);
const items = screen.getAllByRole('listitem');
expect(items).toHaveLength(3);
});<button data-testid="submit-btn">Submit</button>test('finds by test ID', () => {
const button = screen.getByTestId('submit-btn');
expect(button).toBeInTheDocument();
});Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep โข Build Real โข Verify Skills โข Launch Forward