Skip to content

Commit

Permalink
fix: null labels on hidden inputs (#804)
Browse files Browse the repository at this point in the history
* 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.
  • Loading branch information
thomasmarshall authored Nov 3, 2020
1 parent 62f4e5e commit 6ef63b7
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 1 deletion.
7 changes: 7 additions & 0 deletions src/__tests__/label-helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import {getRealLabels} from '../label-helpers'

test('hidden inputs are not labelable', () => {
const element = document.createElement('input')
element.type = 'hidden'
expect(getRealLabels(element)).toEqual([])
})
1 change: 1 addition & 0 deletions src/__tests__/queries.find.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ test('find asynchronously finds elements', async () => {
<div role="dialog"></div>
<div role="meter progressbar"></div>
<header>header</header>
<input type="hidden" />
</div>
`)
await expect(findByLabelText('test-label')).resolves.toBeTruthy()
Expand Down
2 changes: 1 addition & 1 deletion src/label-helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ function getLabelContent(node) {

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

if (!isLabelable(element)) return []

Expand Down

0 comments on commit 6ef63b7

Please sign in to comment.