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
