Dom-testing-library: Support querying by aria-labelledby for tags that aren't <label>

Created on 10 Oct 2018  路  6Comments  路  Source: testing-library/dom-testing-library

Describe the feature you'd like:

https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-labelledby_attribute

The aria-labelledby attribute doesn't require the labeling element to be a <label> tag, but dom-testing-lib only searches for labels in queryByLabelText.

I'd like to add a way to query for anything by ARIA label, which would allow doing things like selecting a card item by its heading text and then doing scoped queries for related elements like an "edit" button.

This would largely replace the need for workarounds like getByText -> .$closest() parent testid.

Suggested implementation:

Describe alternatives you've considered:

Teachability, Documentation, Adoption, Migration Strategy:

enhancement help wanted needs discussion

Most helpful comment

That seems reasonable 馃憤

All 6 comments

Hey Alex 馃憢

Interesting. So would making it so you can pass a custom selector to this call be sufficient?

I don't think so, I think it should be easier to do to encourage the use of aria-labelledby instead of testid.

For performance it might make sense to work backwards from nodes with the aria-labelledby attribute instead of traversing all nodes first. getByText traverses everything though so maybe it's not a big deal.

Would it be a breaking change to change getByLabelText to this:

const possibleLabelNodes = queryAllByText(query);

const ariaLabelledNodes = possibleLabelNodes.reduce(
  (allLabeledNodes, nextLabelNode) => {
    const labelId = nextLabelNode.getAttribute("id");
    if (labelId === undefined) return allLabeledNodes;

    // ARIA labels can label multiple elements
    const labelledNodes = container.querySelectorAll(
      `[aria-labelledby~="${labelId}"]`,
    );

    return allLabeledNodes.concat(labelledNodes);
  },
);
  • Combine the results
return _.uniq([...labelledNodes, ...ariaLabelledNodes])

That seems reasonable 馃憤

:tada: This issue has been resolved in version 3.9.0 :tada:

The release is available on:

Your semantic-release bot :package::rocket:

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nicolasschabram picture nicolasschabram  路  3Comments

eliyaomid picture eliyaomid  路  3Comments

ngbrown picture ngbrown  路  4Comments

kentcdodds picture kentcdodds  路  3Comments

PaulInglis picture PaulInglis  路  3Comments