'When to query inaccessible elements by setting role vs testId vs DOM container in React Testing Library
I understand that the React Testing Library approach is to query for DOM elements in a way that makes sense from a user's perspective (e.g by role or visual text). As well, on the RTL docs, there is a rough priority list of which query method to use when possible.
However, is there a rough priority list / preference for a particular method of querying conventionally inaccessible elements as well? Like, for example, nested divs that contain important styling classes to test.
I'm aware of 3 possible ways:
- By setting a
roleandaria-labelfield, which makes the element accessible via.queryByRole() - Setting a
data-testidfield and then querying via.getByTestId() - Querying the DOM container itself, which you can access via
const { container } = render(<Component />);.
I want to emphasize that I understand these are anti-patterns and should be avoided as much as possible. But, if needed, when is it best to use each of these methods and are there additional alternatives to querying inaccessible elements that should also be considered circumstantially?
Solution 1:[1]
Getting an element by Role and its accessible name should be always preferred. Using semantic HTML there's no need to explicitly set the element role and it the preferred way to define accessible roles. If your element is not available in your accessibility tree, it probably means you are messing up HTML rules (eg. div inside a button is not allowed and makes your button inaccessible). You can validate your HTML using Nu HTML Checker.
When dealing with inputs get the element byLabelText should be the preferred way, because it validate that your input have an accessible label.
Setting a data-testid is the last way to get an element. For instance if you are testing the presence of a panel without any accessible role.
Manipulating directly the DOM is discourage (in my personal experience I never have used it). It should be avoided because DOM structure could vary more frequently than accessible role (eg. for styling purposes) making your tests more fragile.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
