Skip to content

Commit 6ef63b7

Browse files
fix: null labels on hidden inputs (#804)
* Ensure hidden inputs are not labelable The `labels` property on `input` elements of type `hidden` is `null` rather than `NodeList` [1]. This meant the `getRealLabels` function would return `null` causing `queryAllByLabelText` to throw an error when it tried to call `length` on `null` [2]. This commit fixes the issue by ensuring the element is labelable before calling `labels` on it, and adds a test case for this specific scenario. [1]: https://html.spec.whatwg.org/multipage/forms.html#dom-lfe-labels [2]: https://github.com/testing-library/dom-testing-library/blob/62f4e5e09a4b81ef66679560b540523edccdef98/src/queries/label-text.js#L52 * squash! Ensure hidden inputs are not labelable This commit fixes the issue by retuning an empty array if the `labels` property is `null`, and adds a test case for this specific scenario.
1 parent 62f4e5e commit 6ef63b7

File tree

3 files changed

+9
-1
lines changed

3 files changed

+9
-1
lines changed

src/__tests__/label-helpers.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import {getRealLabels} from '../label-helpers'
2+
3+
test('hidden inputs are not labelable', () => {
4+
const element = document.createElement('input')
5+
element.type = 'hidden'
6+
expect(getRealLabels(element)).toEqual([])
7+
})

src/__tests__/queries.find.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ test('find asynchronously finds elements', async () => {
3535
<div role="dialog"></div>
3636
<div role="meter progressbar"></div>
3737
<header>header</header>
38+
<input type="hidden" />
3839
</div>
3940
`)
4041
await expect(findByLabelText('test-label')).resolves.toBeTruthy()

src/label-helpers.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ function getLabelContent(node) {
3434

3535
// Based on https://github.com/eps1lon/dom-accessibility-api/pull/352
3636
function getRealLabels(element) {
37-
if (element.labels !== undefined) return element.labels
37+
if (element.labels !== undefined) return element.labels ?? []
3838

3939
if (!isLabelable(element)) return []
4040

0 commit comments

Comments
 (0)