-
Notifications
You must be signed in to change notification settings - Fork 470
/
Copy pathtext.ts
86 lines (81 loc) · 2.59 KB
/
text.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
76
77
78
79
80
81
82
83
84
85
86
import {wrapAllByQueryWithSuggestion} from '../query-helpers'
import {checkContainerType} from '../helpers'
import {
AllByText,
GetErrorFunction,
SelectorMatcherOptions,
Matcher,
} from '../../types'
import {
fuzzyMatches,
matches,
getConfig,
makeNormalizer,
getNodeText,
buildQueries,
} from './all-utils'
const queryAllByText: AllByText = (
container,
text,
{
selector = '*',
exact = true,
collapseWhitespace,
trim,
ignore = getConfig().defaultIgnore,
normalizer,
} = {},
) => {
checkContainerType(container)
const matcher = exact ? matches : fuzzyMatches
const matchNormalizer = makeNormalizer({collapseWhitespace, trim, normalizer})
let baseArray: HTMLElement[] = []
if (typeof container.matches === 'function' && container.matches(selector)) {
baseArray = [container]
}
return (
[
...baseArray,
...Array.from(
getConfig().queryAllElements<HTMLElement, HTMLElement>(
container,
selector,
),
),
]
// TODO: `matches` according lib.dom.d.ts can get only `string` but according our code it can handle also boolean :)
.filter(node => !ignore || !node.matches(ignore as string))
.filter(node => matcher(getNodeText(node), node, text, matchNormalizer))
)
}
const getMultipleError: GetErrorFunction<[unknown]> = (c, text) =>
`Found multiple elements with the text: ${text}`
const getMissingError: GetErrorFunction<[Matcher, SelectorMatcherOptions]> = (
c,
text,
options = {},
) => {
const {collapseWhitespace, trim, normalizer} = options
const matchNormalizer = makeNormalizer({collapseWhitespace, trim, normalizer})
const normalizedText = matchNormalizer(text.toString())
const isNormalizedDifferent = normalizedText !== text.toString()
return `Unable to find an element with the text: ${
isNormalizedDifferent
? `${normalizedText} (normalized from '${text}')`
: text
}. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.`
}
const queryAllByTextWithSuggestions = wrapAllByQueryWithSuggestion<
// @ts-expect-error -- See `wrapAllByQueryWithSuggestion` Argument constraint comment
[text: Matcher, options?: MatcherOptions]
>(queryAllByText, queryAllByText.name, 'queryAll')
const [queryByText, getAllByText, getByText, findAllByText, findByText] =
buildQueries(queryAllByText, getMultipleError, getMissingError)
export {
queryByText,
queryAllByTextWithSuggestions as queryAllByText,
getByText,
getAllByText,
findAllByText,
findByText,
}