Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This is a mix of RFC, feature request and personal experience when writing tests. Maybe I'm missing something obvious about getByText but I do not find this query useful in its current state.
What:
Add
*ByTextContent
queryWhy:
Simpler, more user centric API for finding elements with a given
textContent
How:
Simply iterate over all elements matching the given selector and comparing with
textContent
(exact).Checklist:
docs site
I think getNodeText is currently overly complex which can lead to surprising behavior in
*ByText
queries.Consider the following button:
<button><span>Button</span></button>
or a bit more convoluted<button><span>But</span><span>ton</span></button>
. Both of these have atextContent
ofButton
but eithergetByText
returns thespan
for the former case or null for the latter case.I suspect that the current implementation tries to avoid including wrapper divs in e.g.
<div class="wrapper"><p>Text</p></div>
. I understood those query helpers as a11y first helpers which means it would be sufficient to matchtextContent
and then let the user define meaningful selectors.This would encourage thinking about using more semantic elements e.g. if
getByTextContent('Text')
returns multiple spans and divs with the same content one of those should be made a paragraph or given an aria role etc.Intuitively a user centric approach to testing what happens when the user clicks the button that says "Click me" would just query for getByTextContent('Click me', 'button'). The second argument would be a selector. No normalization config, no exact option etc. All of this can be expressed via
TextMatch
.It's IMO ok to fail if surrounding whitespaces changes. Whitespace can change how the user perceives the text (see css
whitespace
) and the test should reflect that. In a perfect worldjsdom
could implementinnerText
and we could use that (it includes layout, whitespace trimming etc).