I would like to get dd
tag by role using the testing library
<dl>
<dt>ID</dt>
<dd>123456</dd>
</dl>
I tried:
screen.getByRole('term', { name: 'ID' })
and
screen.getByRole('definition', { name: 'ID' })
But it didn't work
TestingLibraryElementError: Unable to find an accessible element with the role "definition" and name "ID"
Here are the accessible roles:
term:
Name "":
<dt/>
--------------------------------------------------
definition:
Name "":
<dd/>
--------------------------------------------------
The code below works just fine, but it finds the first element and there can be more than one
screen.getByRole('definition')
To select an element ...ByRole("...", { name })
it needs to have an accessible name. The W3 guidance (for dd
/role="definition"
and dt
/role="term"
; dl
has no implicit ARIA role) says:
role | Necessity of Naming | Guidance |
---|---|---|
definition |
Recommended | Reference the term being defined with role="term" , using aria-labelledby . |
term |
Do Not Name | Since a term is usually the name for the role="definition" element, it could be confusing if the term itself also has a name. |
Therefore you cannot select a term by name, but could select a definition by name if it was labelled by the appropriate term(s):
import { render, screen } from "@testing-library/react";
it("finds the definition by role", () => {
render(
<dl>
<dt id="a">Denim (semigloss finish)</dt>
<dd aria-labelledby="a">Ceiling</dd>
<dt id="b">Denim (eggshell finish)</dt>
<dt id="c">Evening Sky (eggshell finish)</dt>
<dd aria-labelledby="b c">Layered on the walls</dd>
</dl>
);
expect(
screen.getByRole("definition", { name: "Denim (semigloss finish)" })
).toBeInTheDocument();
});
Note that Testing Library uses aria-query
to make these selections.