Skip to content

fix: use the first label for LabelText query suggestions #672

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/__tests__/suggestions.js
Original file line number Diff line number Diff line change
Expand Up @@ -485,3 +485,26 @@ test('getSuggestedQuery does not create suggestions for script and style element
expect(getSuggestedQuery(script, 'get', 'TestId')).toBeUndefined()
expect(getSuggestedQuery(style, 'get', 'TestId')).toBeUndefined()
})

// this is only a temporary fix. The problem is that at the moment @testing-library/dom
// not support label concatenation
// see https://github.com/testing-library/dom-testing-library/issues/545
test('should get the first label with aria-labelledby contains multiple ids', () => {
const {container} = renderIntoDocument(`
<div id="one">One</div>
<div id="two">One</div>
<input
type="text"
aria-labelledby="one two"
/>
`)

expect(
getSuggestedQuery(container.querySelector('input'), 'get', 'labelText'),
).toMatchObject({
queryName: 'LabelText',
queryMethod: 'getByLabelText',
queryArgs: [/one/i],
variant: 'get',
})
})
6 changes: 5 additions & 1 deletion src/suggestions.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,13 @@ function getLabelTextFor(element) {
if (!label) {
const ariaLabelledBy = element.getAttribute('aria-labelledby')
if (ariaLabelledBy) {
// this is only a temporary fix. The problem is that at the moment @testing-library/dom
// not support label concatenation
// see https://github.com/testing-library/dom-testing-library/issues/545
const firstId = ariaLabelledBy.split(' ')[0]
// we're using this notation because with the # selector we would have to escape special characters e.g. user.name
// see https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector#Escaping_special_characters
label = document.querySelector(`[id=${ariaLabelledBy}]`)
label = document.querySelector(`[id="${firstId}"]`)
}
}

Expand Down