From b41ebdd9f51c51c3944bc889018772ee0a5388b8 Mon Sep 17 00:00:00 2001
From: Raphael Lemieux <1904889+raplemie@users.noreply.github.com>
Date: Thu, 18 Aug 2022 10:36:17 -0400
Subject: [PATCH] feat: enhance byText error with `selector`
---
src/__tests__/element-queries.js | 11 ++++++++++-
src/queries/text.ts | 5 ++++-
2 files changed, 14 insertions(+), 2 deletions(-)
diff --git a/src/__tests__/element-queries.js b/src/__tests__/element-queries.js
index 83a897f4..364de4aa 100644
--- a/src/__tests__/element-queries.js
+++ b/src/__tests__/element-queries.js
@@ -76,6 +76,15 @@ test('get throws a useful error message', () => {
`)
+ 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
+
+ `)
expect(() => getByTestId('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`
Unable to find an element by: [data-testid="LucyRicardo"]
@@ -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
diff --git a/src/queries/text.ts b/src/queries/text.ts
index e0282844..41594ce7 100644
--- a/src/queries/text.ts
+++ b/src/queries/text.ts
@@ -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.`
}