Skip to content

Commit 373dbc4

Browse files
authored
fix: use the first label for LabelText query suggestions (#672)
* test: add failing test * fix: add quotes between selector * refactor: get first id from aria-labelledby Closes testing-library/testing-playground#214
1 parent 6bc8e2e commit 373dbc4

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/__tests__/suggestions.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -485,3 +485,26 @@ test('getSuggestedQuery does not create suggestions for script and style element
485485
expect(getSuggestedQuery(script, 'get', 'TestId')).toBeUndefined()
486486
expect(getSuggestedQuery(style, 'get', 'TestId')).toBeUndefined()
487487
})
488+
489+
// this is only a temporary fix. The problem is that at the moment @testing-library/dom
490+
// not support label concatenation
491+
// see https://github.com/testing-library/dom-testing-library/issues/545
492+
test('should get the first label with aria-labelledby contains multiple ids', () => {
493+
const {container} = renderIntoDocument(`
494+
<div id="one">One</div>
495+
<div id="two">One</div>
496+
<input
497+
type="text"
498+
aria-labelledby="one two"
499+
/>
500+
`)
501+
502+
expect(
503+
getSuggestedQuery(container.querySelector('input'), 'get', 'labelText'),
504+
).toMatchObject({
505+
queryName: 'LabelText',
506+
queryMethod: 'getByLabelText',
507+
queryArgs: [/one/i],
508+
variant: 'get',
509+
})
510+
})

src/suggestions.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,13 @@ function getLabelTextFor(element) {
1515
if (!label) {
1616
const ariaLabelledBy = element.getAttribute('aria-labelledby')
1717
if (ariaLabelledBy) {
18+
// this is only a temporary fix. The problem is that at the moment @testing-library/dom
19+
// not support label concatenation
20+
// see https://github.com/testing-library/dom-testing-library/issues/545
21+
const firstId = ariaLabelledBy.split(' ')[0]
1822
// we're using this notation because with the # selector we would have to escape special characters e.g. user.name
1923
// see https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector#Escaping_special_characters
20-
label = document.querySelector(`[id=${ariaLabelledBy}]`)
24+
label = document.querySelector(`[id="${firstId}"]`)
2125
}
2226
}
2327

0 commit comments

Comments
 (0)