Skip to content

Commit

Permalink
feat: enhance byText missing error (#1117)
Browse files Browse the repository at this point in the history
  • Loading branch information
MatanBobi committed Mar 26, 2022
1 parent 90d420d commit 77125fd
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
9 changes: 9 additions & 0 deletions src/__tests__/element-queries.js
Expand Up @@ -57,6 +57,15 @@ test('get throws a useful error message', () => {
<div />
</div>
`)
expect(() => getByText('Lucy Ricardo'))
.toThrowErrorMatchingInlineSnapshot(`
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.
Ignored nodes: comments, <script />, <style />
<div>
<div />
</div>
`)
expect(() => getByTestId('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`
Unable to find an element by: [data-testid="LucyRicardo"]
Expand Down
24 changes: 21 additions & 3 deletions src/queries/text.ts
@@ -1,7 +1,12 @@
import {wrapAllByQueryWithSuggestion} from '../query-helpers'
import {checkContainerType} from '../helpers'
import {DEFAULT_IGNORE_TAGS} from '../shared'
import {AllByText, GetErrorFunction} from '../../types'
import {
AllByText,
GetErrorFunction,
SelectorMatcherOptions,
Matcher,
} from '../../types'
import {
fuzzyMatches,
matches,
Expand Down Expand Up @@ -42,8 +47,21 @@ const queryAllByText: AllByText = (

const getMultipleError: GetErrorFunction<[unknown]> = (c, text) =>
`Found multiple elements with the text: ${text}`
const getMissingError: GetErrorFunction<[unknown]> = (c, text) =>
`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.`
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
Expand Down

0 comments on commit 77125fd

Please sign in to comment.