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.
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:
Remove this part: https://github.com/kentcdodds/dom-testing-library/blob/7b57f7313c3e751ad10e7ac8198ccc9b381cf82f/src/queries.js#L47-L52
Add something that does the same thing using queryAllByText as the initial filter?
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);
},
);
return _.uniq([...labelledNodes, ...ariaLabelledNodes])
That seems reasonable 馃憤
:tada: This issue has been resolved in version 3.9.0 :tada:
The release is available on:
npm package (@latest dist-tag)Your semantic-release bot :package::rocket:
Most helpful comment
That seems reasonable 馃憤