forked from testing-library/dom-testing-library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdisplay-value.ts
75 lines (70 loc) · 2.12 KB
/
display-value.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import {wrapAllByQueryWithSuggestion} from '../query-helpers'
import {checkContainerType} from '../helpers'
import {
AllByBoundAttribute,
GetErrorFunction,
Matcher,
MatcherOptions,
} from '../../types'
import {
querySelectorAll,
getNodeText,
matches,
fuzzyMatches,
makeNormalizer,
buildQueries,
} from './all-utils'
const queryAllByDisplayValue: AllByBoundAttribute = (
container,
value,
{exact = true, collapseWhitespace, trim, normalizer} = {},
) => {
checkContainerType(container)
const matcher = exact ? matches : fuzzyMatches
const matchNormalizer = makeNormalizer({collapseWhitespace, trim, normalizer})
return Array.from(
querySelectorAll<HTMLElement, HTMLElement>(
container,
`input,textarea,select`,
),
).filter(node => {
if (node.tagName === 'SELECT') {
const selectedOptions = Array.from(
(node as HTMLSelectElement).options,
).filter(option => option.selected)
return selectedOptions.some(optionNode =>
matcher(getNodeText(optionNode), optionNode, value, matchNormalizer),
)
} else {
return matcher(
(node as HTMLInputElement).value,
node,
value,
matchNormalizer,
)
}
})
}
const getMultipleError: GetErrorFunction<[unknown]> = (c, value) =>
`Found multiple elements with the display value: ${value}.`
const getMissingError: GetErrorFunction<[unknown]> = (c, value) =>
`Unable to find an element with the display value: ${value}.`
const queryAllByDisplayValueWithSuggestions = wrapAllByQueryWithSuggestion<
// @ts-expect-error -- See `wrapAllByQueryWithSuggestion` Argument constraint comment
[value: Matcher, options?: MatcherOptions]
>(queryAllByDisplayValue, queryAllByDisplayValue.name, 'queryAll')
const [
queryByDisplayValue,
getAllByDisplayValue,
getByDisplayValue,
findAllByDisplayValue,
findByDisplayValue,
] = buildQueries(queryAllByDisplayValue, getMultipleError, getMissingError)
export {
queryByDisplayValue,
queryAllByDisplayValueWithSuggestions as queryAllByDisplayValue,
getByDisplayValue,
getAllByDisplayValue,
findAllByDisplayValue,
findByDisplayValue,
}