Skip to content

Commit

Permalink
feat: Enhance ByText error with selector (#1159)
Browse files Browse the repository at this point in the history
  • Loading branch information
raplemie committed Oct 8, 2022
1 parent a9a8cf2 commit d1a57dd
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
11 changes: 10 additions & 1 deletion src/__tests__/element-queries.js
Expand Up @@ -76,6 +76,15 @@ test('get throws a useful error message', () => {
<div />
</div>
`)
expect(() => getByText('LucyRicardo', {selector: 'span'}))
.toThrowErrorMatchingInlineSnapshot(`
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.
Ignored nodes: comments, script, style
<div>
<div />
</div>
`)
expect(() => getByTestId('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`
Unable to find an element by: [data-testid="LucyRicardo"]
Expand Down Expand Up @@ -1297,7 +1306,7 @@ test('ByText error message ignores not the same elements as configured in `ignor
expect(() =>
getByText('.css-selector', {selector: 'style', ignore: 'script'}),
).toThrowErrorMatchingInlineSnapshot(`
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.
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.
Ignored nodes: comments, script, style
<body>
Expand Down
5 changes: 4 additions & 1 deletion src/queries/text.ts
Expand Up @@ -52,14 +52,17 @@ const getMissingError: GetErrorFunction<[Matcher, SelectorMatcherOptions]> = (
text,
options = {},
) => {
const {collapseWhitespace, trim, normalizer} = options
const {collapseWhitespace, trim, normalizer, selector} = options
const matchNormalizer = makeNormalizer({collapseWhitespace, trim, normalizer})
const normalizedText = matchNormalizer(text.toString())
const isNormalizedDifferent = normalizedText !== text.toString()
const isCustomSelector = (selector ?? '*') !== '*'
return `Unable to find an element with the text: ${
isNormalizedDifferent
? `${normalizedText} (normalized from '${text}')`
: text
}${
isCustomSelector ? `, which matches selector '${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.`
}

Expand Down

0 comments on commit d1a57dd

Please sign in to comment.