Skip to content

Commit 732a8ab

Browse files
author
Bianca Del Carretto
committed
get concat label through labels combination (testing-library#545)
1 parent b609b32 commit 732a8ab

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

src/__tests__/element-queries.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,8 @@ test('can get form controls by label text', () => {
171171
<div>
172172
<input id="sixth-label-one" value="6th one"/>
173173
<input id="sixth-label-two" value="6th two"/>
174-
<input aria-labelledby="sixth-label-one sixth-label-two" id="sixth-id" />
174+
<label id="sixth-label-three">6th three</label>
175+
<input aria-labelledby="sixth-label-one sixth-label-two sixth-label-three" id="sixth-id" />
175176
</div>
176177
</div>
177178
`)
@@ -183,6 +184,7 @@ test('can get form controls by label text', () => {
183184
expect(getByLabelText('5th two').id).toBe('fifth-id')
184185
expect(getByLabelText('6th one').id).toBe('sixth-id')
185186
expect(getByLabelText('6th two').id).toBe('sixth-id')
187+
expect(getByLabelText('6th one 6th two 6th three').id).toBe('sixth-id')
186188
})
187189

188190
test('can get elements labelled with aria-labelledby attribute', () => {

src/queries/label-text.js

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,21 @@ import {
1212
} from './all-utils'
1313
import {queryAllByText} from './text'
1414

15+
function getCombinations(labels, matcher) {
16+
const combs = [[]]
17+
const matching = []
18+
for (const label of labels) {
19+
const copy = [...combs] // See note below.
20+
for (const prefix of copy) {
21+
const combination = prefix.concat(label.textToMatch)
22+
combs.push(combination)
23+
if (matcher(combination.join(' '), label.node)) {
24+
matching.push(label.node)
25+
}
26+
}
27+
}
28+
return matching
29+
}
1530
function queryAllLabels(container) {
1631
return Array.from(container.querySelectorAll('label,input'))
1732
.map(node => {
@@ -45,11 +60,25 @@ function queryAllLabelsByText(
4560

4661
const textToMatchByLabels = queryAllLabels(container)
4762

48-
return textToMatchByLabels
63+
const nodesByLabelMatchingText = textToMatchByLabels
4964
.filter(({node, textToMatch}) =>
5065
matcher(textToMatch, node, text, matchNormalizer),
5166
)
5267
.map(({node}) => node)
68+
const labelsNotMatchingTextAndNotEmpty = textToMatchByLabels.filter(
69+
({node, textToMatch}) =>
70+
Boolean(textToMatch) &&
71+
nodesByLabelMatchingText.findIndex(nodeByLabelByText =>
72+
nodeByLabelByText.isEqualNode(node),
73+
) === -1,
74+
)
75+
76+
const concatLabelsMatching = getCombinations(
77+
labelsNotMatchingTextAndNotEmpty,
78+
(textToMatch, node) => matcher(textToMatch, node, text, matchNormalizer),
79+
)
80+
81+
return nodesByLabelMatchingText.concat(concatLabelsMatching)
5382
}
5483

5584
function queryAllByLabelText(

0 commit comments

Comments
 (0)