liveBook · Manning

getByRole

As explained in React in Depth

getByRole is a React Testing Library query function that finds an element by its semantic role and optionally its accessible name.

getByRole finds rendered elements through ARIA roles rather than implementation-specific selectors. Roles describe how elements are understood and interacted with programmatically; an accessible name can further narrow the match. section 10.1

Scoped role queries in MenuItem

Render a MenuItem, locate its list item with screen.getByRole("listitem"), then call getByRole(listItem, "link") to inspect the nested link’s href, title, and text. A role query can also include an accessible name, such as screen.getByRole("listitem", { name: "Blog" }). section 10.1

Listing 10.1 Unit-testing MenuItem
import {    #1
  render,    #1
  screen,   #1
  getByRole,  #1  
} from "@testing-library/react";   #1
import "@testing-library/jest-dom";    #2
import MenuItem from "./MenuItem";     #3
test(    #4
  "MenuItem renders a link in a list item",   #4
  () => {   #4
  // ARRANGE
  render(<MenuItem href="/blog" label="Blog" />);    #5
  // ASSERT
  const listItem = screen.getByRole("listitem");  #6
  const link = getByRole(listItem, "link");    #6
  expect(link).toHaveAttribute("href", "/blog");     #7
  expect(link).toHaveAttribute("title", "Blog");   #7
  expect(link).toHaveTextContent("Blog");   #7
});

Runnable test showing render, screen.getByRole, a scoped getByRole call, and Jest DOM assertions. section 10.1

How React in Depth covers it

How deep it goes
Explains ARIA roles and demonstrates scoped and named queries, but defers most WAI-ARIA specification detail.
Examples
Tests a MenuItem link nested inside a list item and verifies its href, title, and text.
What it assumes
Assumes React component testing familiarity while introducing ARIA roles as programmatic access points.
What you can do after
Apply it via React Testing Library to locate accessible elements and assert their rendered properties.
How it connects
Connects ARIA roles with accessible names, screen, render, and Jest DOM assertions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React in Depth. The section links point to the parts of the book it draws on.