Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
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:

  1. By setting a role and aria-label field, which makes the element accessible via .queryByRole()
  2. Setting a data-testid field and then querying via .getByTestId()
  3. 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?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!