testing-library / dom-testing-library

🐙 Simple and complete DOM testing utilities that encourage good testing practices.
https://testing-library.com/dom
MIT License
3.26k stars 467 forks source link

Display provided `selector` in *ByText error message #1158

Closed raplemie closed 1 year ago

raplemie commented 2 years ago

Describe the feature you'd like:

When getByText returns an error message it currently does not mention if any selector other than "*" was provided to the query and returns the prettied body. (Where you might actually see the text you are looking for...)

Adding any selector different than "*" might bring attention to them to the reviewer of the test straight from the error message and help understand why it wasnt found.

Suggested implementation:

In src/queries/text.ts:

const getMissingError: GetErrorFunction<[Matcher, SelectorMatcherOptions]> = (
  c,
  text,
  options = {},
) => {
  const {collapseWhitespace, trim, normalizer, selector} = options
  const matchNormalizer = makeNormalizer({collapseWhitespace, trim, normalizer})
  const normalizedText = matchNormalizer(text.toString())
  const isNormalizedDifferent = normalizedText !== text.toString()
  const isUsingSelector = selector !== "*";
  return `Unable to find an element with the text: ${
    isNormalizedDifferent
      ? `${normalizedText} (normalized from '${text}')`
      : text
  }${
    isUsingSelector
      ? `, which satisfies 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.`
}

Describe alternatives you've considered:

I did not see much alternatives to draw attention to the selector other than this suggestion.

Teachability, Documentation, Adoption, Migration Strategy:

As this is only adding information to the error messages if a praticular feature is used, I doubt the documentation would require any change, adoption or migration, unless the messages are parsed in some way...

github-actions[bot] commented 1 year ago

:tada: This issue has been resolved in version 8.19.0 :tada:

The release is available on:

Your semantic-release bot :package::rocket: