Skip to content

Commit d1a57dd

Browse files
authored
feat: Enhance ByText error with selector (#1159)
1 parent a9a8cf2 commit d1a57dd

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

src/__tests__/element-queries.js

+10-1
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,15 @@ test('get throws a useful error message', () => {
7676
<div />
7777
</div>
7878
`)
79+
expect(() => getByText('LucyRicardo', {selector: 'span'}))
80+
.toThrowErrorMatchingInlineSnapshot(`
81+
Unable to find an element with the text: LucyRicardo, which matches selector 'span'. 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.
82+
83+
Ignored nodes: comments, script, style
84+
<div>
85+
<div />
86+
</div>
87+
`)
7988
expect(() => getByTestId('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`
8089
Unable to find an element by: [data-testid="LucyRicardo"]
8190
@@ -1297,7 +1306,7 @@ test('ByText error message ignores not the same elements as configured in `ignor
12971306
expect(() =>
12981307
getByText('.css-selector', {selector: 'style', ignore: 'script'}),
12991308
).toThrowErrorMatchingInlineSnapshot(`
1300-
Unable to find an element with the text: .css-selector. 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.
1309+
Unable to find an element with the text: .css-selector, which matches selector 'style'. 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.
13011310
13021311
Ignored nodes: comments, script, style
13031312
<body>

src/queries/text.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -52,14 +52,17 @@ const getMissingError: GetErrorFunction<[Matcher, SelectorMatcherOptions]> = (
5252
text,
5353
options = {},
5454
) => {
55-
const {collapseWhitespace, trim, normalizer} = options
55+
const {collapseWhitespace, trim, normalizer, selector} = options
5656
const matchNormalizer = makeNormalizer({collapseWhitespace, trim, normalizer})
5757
const normalizedText = matchNormalizer(text.toString())
5858
const isNormalizedDifferent = normalizedText !== text.toString()
59+
const isCustomSelector = (selector ?? '*') !== '*'
5960
return `Unable to find an element with the text: ${
6061
isNormalizedDifferent
6162
? `${normalizedText} (normalized from '${text}')`
6263
: text
64+
}${
65+
isCustomSelector ? `, which matches selector '${selector}'` : ''
6366
}. 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.`
6467
}
6568

0 commit comments

Comments
 (0)