Skip to content

fix aria-labelledby with not found id #711

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
27 changes: 27 additions & 0 deletions src/__tests__/element-queries.js
Original file line number Diff line number Diff line change
Expand Up @@ -1045,3 +1045,30 @@ test('can get an element with aria-labelledby when label has a child', () => {
'2nd-input',
)
})
test('gets an element when there is an aria-labelledby a not found id', () => {
const {getByLabelText} = render(`
<div>
<input aria-labelledby="not-existing-label"/>
<label id="existing-label">Test</label>
<input aria-labelledby="existing-label" id="input-id" />
</div>
`)
expect(getByLabelText('Test').id).toBe('input-id')
})

test('return a proper error message when no label is found and there is an aria-labelledby a not found id', () => {
const {getByLabelText} = render(
'<input aria-labelledby="not-existing-label"/>',
)

expect(() => getByLabelText('LucyRicardo'))
.toThrowErrorMatchingInlineSnapshot(`
"Unable to find a label with the text of: LucyRicardo

<div>
<input
aria-labelledby="not-existing-label"
/>
</div>"
`)
})
9 changes: 6 additions & 3 deletions src/queries/label-text.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,12 @@ function queryAllByLabelText(
const labelsId = labelledElement.getAttribute('aria-labelledby')
? labelledElement.getAttribute('aria-labelledby').split(' ')
: []
const labelsValue = labelsId.length
let labelsValue = labelsId.length
? labelsId.map(labelId => {
const labellingElement = container.querySelector(`[id="${labelId}"]`)
return getLabelContent(labellingElement)
const labellingElement = container.querySelector(
`[id="${labelId}"]`,
)
return labellingElement ? getLabelContent(labellingElement) : ''
})
: Array.from(labelledElement.labels).map(label => {
const textToMatch = getLabelContent(label)
Expand All @@ -99,6 +101,7 @@ function queryAllByLabelText(
}
return textToMatch
})
labelsValue = labelsValue.filter(Boolean)
if (
matcher(labelsValue.join(' '), labelledElement, text, matchNormalizer)
)
Expand Down