Ojasa Mirai

Ojasa Mirai

ReactJS

Loading...

Learning Level

๐ŸŸข Beginner๐Ÿ”ต Advanced
๐Ÿงช Testing Basics๐ŸŽจ Rendering Components๐Ÿ” Querying Elements๐Ÿ‘† Simulating Events๐Ÿงช Async Testing๐ŸŽญ Mocking๐Ÿงช Test Organization๐Ÿงช Testing Best Practices
Reactjs/Testing/Querying Elements

๐Ÿ” Querying Elements with Jest

Learn the best ways to find elements in tests.

Query Priority

1. getByRole - Most semantic (recommended)

2. getByLabelText - For form labels

3. getByPlaceholderText - For placeholder text

4. getByText - For other text

5. getByTestId - Last resort

Query Methods

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');

Advanced Queries

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);
});

Using Test IDs

<button data-testid="submit-btn">Submit</button>
test('finds by test ID', () => {
  const button = screen.getByTestId('submit-btn');
  expect(button).toBeInTheDocument();
});

โœ… Key Takeaways

  • Prefer **getByRole** for semantic queries
  • Use **getByLabelText** for forms
  • Use **queryBy** to check non-existence
  • Use **findBy** for async elements
  • Avoid **getByTestId** unless necessary

Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

ยฉ 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn