Skip to content

getByText()/queryByText() (or some new query) should search across nested elements #201

Closed
@helixbass

Description

@helixbass

Describe the feature you'd like:

In my app, I'm rendering some markup like:

<div>
  <span>a. </span>
  <span class="something">Here is the answer text.</span>
</div>

It feels like I should be able to test that the right "answer prefix" (here, "a.") is rendered with the corresponding answer text just by doing eg:

getByText(/a\. Here is the answer text\./)

(which would select the enclosing <div>)

So I guess recursively concatenating text node children from nested elements?

It didn't look like there's already a way to do this

Suggested implementation:

I haven't looked at the implementation, just checked that in __tests__/element-queries.js I saw a test for sibling text node concatenation but not for nested child element text nodes

Would possibly be up for implementing this but am not super familiar with low-level DOM APIs

Describe alternatives you've considered:

I guess adding a data-testid to the enclosing <div> and then examining its children individually? But in the spirit of "what matters is how the user experiences it", that seems fragile compared to just searching text content across whatever arbitrary nested markup you may be rendering

Teachability, Documentation, Adoption, Migration Strategy:

I think adding an example with simple nested content eg:

<div>Some <span>nested</span> text</div>

with

getByText(/Some nested text/)

would be pretty clear as far as the gist of the supported feature

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions