Skip to content

Commit 38fc55c

Browse files
author
Bianca Del Carretto
committed
fix aria-labelledby with not found id (#710)
1 parent 4afb456 commit 38fc55c

File tree

2 files changed

+33
-3
lines changed

2 files changed

+33
-3
lines changed

src/__tests__/element-queries.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1045,3 +1045,30 @@ test('can get an element with aria-labelledby when label has a child', () => {
10451045
'2nd-input',
10461046
)
10471047
})
1048+
test('gets an element when there is an aria-labelledby a not found id', () => {
1049+
const {getByLabelText} = render(`
1050+
<div>
1051+
<input aria-labelledby="not-existing-label"/>
1052+
<label id="existing-label">Test</label>
1053+
<input aria-labelledby="existing-label" id="input-id" />
1054+
</div>
1055+
`)
1056+
expect(getByLabelText('Test').id).toBe('input-id')
1057+
})
1058+
1059+
test('return a proper error message when no label is found and there is an aria-labelledby a not found id', () => {
1060+
const {getByLabelText} = render(
1061+
'<input aria-labelledby="not-existing-label"/>',
1062+
)
1063+
1064+
expect(() => getByLabelText('LucyRicardo'))
1065+
.toThrowErrorMatchingInlineSnapshot(`
1066+
"Unable to find a label with the text of: LucyRicardo
1067+
1068+
<div>
1069+
<input
1070+
aria-labelledby="not-existing-label"
1071+
/>
1072+
</div>"
1073+
`)
1074+
})

src/queries/label-text.js

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,10 +79,12 @@ function queryAllByLabelText(
7979
const labelsId = labelledElement.getAttribute('aria-labelledby')
8080
? labelledElement.getAttribute('aria-labelledby').split(' ')
8181
: []
82-
const labelsValue = labelsId.length
82+
let labelsValue = labelsId.length
8383
? labelsId.map(labelId => {
84-
const labellingElement = container.querySelector(`[id="${labelId}"]`)
85-
return getLabelContent(labellingElement)
84+
const labellingElement = container.querySelector(
85+
`[id="${labelId}"]`,
86+
)
87+
return labellingElement ? getLabelContent(labellingElement) : ''
8688
})
8789
: Array.from(labelledElement.labels).map(label => {
8890
const textToMatch = getLabelContent(label)
@@ -99,6 +101,7 @@ function queryAllByLabelText(
99101
}
100102
return textToMatch
101103
})
104+
labelsValue = labelsValue.filter(Boolean)
102105
if (
103106
matcher(labelsValue.join(' '), labelledElement, text, matchNormalizer)
104107
)

0 commit comments

Comments
 (0)