Skip to content

Commit 77125fd

Browse files
authored
feat: enhance byText missing error (#1117)
1 parent 90d420d commit 77125fd

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

src/__tests__/element-queries.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,15 @@ test('get throws a useful error message', () => {
5757
<div />
5858
</div>
5959
`)
60+
expect(() => getByText('Lucy Ricardo'))
61+
.toThrowErrorMatchingInlineSnapshot(`
62+
Unable to find an element with the text: Lucy Ricardo (normalized from 'Lucy Ricardo'). 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.
63+
64+
Ignored nodes: comments, <script />, <style />
65+
<div>
66+
<div />
67+
</div>
68+
`)
6069
expect(() => getByTestId('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`
6170
Unable to find an element by: [data-testid="LucyRicardo"]
6271

src/queries/text.ts

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
import {wrapAllByQueryWithSuggestion} from '../query-helpers'
22
import {checkContainerType} from '../helpers'
33
import {DEFAULT_IGNORE_TAGS} from '../shared'
4-
import {AllByText, GetErrorFunction} from '../../types'
4+
import {
5+
AllByText,
6+
GetErrorFunction,
7+
SelectorMatcherOptions,
8+
Matcher,
9+
} from '../../types'
510
import {
611
fuzzyMatches,
712
matches,
@@ -42,8 +47,21 @@ const queryAllByText: AllByText = (
4247

4348
const getMultipleError: GetErrorFunction<[unknown]> = (c, text) =>
4449
`Found multiple elements with the text: ${text}`
45-
const getMissingError: GetErrorFunction<[unknown]> = (c, text) =>
46-
`Unable to find an element with the 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.`
50+
const getMissingError: GetErrorFunction<[Matcher, SelectorMatcherOptions]> = (
51+
c,
52+
text,
53+
options = {},
54+
) => {
55+
const {collapseWhitespace, trim, normalizer} = options
56+
const matchNormalizer = makeNormalizer({collapseWhitespace, trim, normalizer})
57+
const normalizedText = matchNormalizer(text.toString())
58+
const isNormalizedDifferent = normalizedText !== text.toString()
59+
return `Unable to find an element with the text: ${
60+
isNormalizedDifferent
61+
? `${normalizedText} (normalized from '${text}')`
62+
: text
63+
}. 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.`
64+
}
4765

4866
const queryAllByTextWithSuggestions = wrapAllByQueryWithSuggestion<
4967
// @ts-expect-error -- See `wrapAllByQueryWithSuggestion` Argument constraint comment

0 commit comments

Comments
 (0)