How to find input by span in React-testing-library?
Asked Answered
C

3

5

How can I find the checkbox for by text from span element? I can't modify my HTML. I wish test fireEvent on input element.

`

<label>
   <div>
      <input type="checkbox" class="checkbox-extra-style">
      <span> SPAN A</span>
   </div>
</label>
<label>
   <div>
      <input type="checkbox" class="checkbox-extra-style">
      <span> SPAN B</span>
   </div>
</label>

` ....

Thanks a lot for any help.

Chutzpah answered 13/10, 2020 at 14:26 Comment(0)
S
8

Span has no aria role, so you have a couple of options:

  1. Modify the html adding an aria-role to the span, then use screen.getByRole
  2. Let the HTML as it is, and following the priority list use screen.getByText("SPAN A")
Syndesmosis answered 9/12, 2021 at 12:14 Comment(2)
Thanks for tips Borja!Chutzpah
Upvote for the correct order of solutions according to RTL best practiceIthyphallic
R
4

You should use the extra options that are available in the getBy... queries. For example, in this case, screen.getByRole("checkbox", { name: /span a /i }). This will select

  1. checkboxes by role on the page
  2. filter the above down to the specific checkbox that has the text "SPAN A" associated with it ("SPAN A" will be the name since the span and the input are both inside the same label).

For additional help in finding out the right query to use for some given HTML, testing-library's testing playground is a great resource.

Ravi answered 27/10, 2020 at 14:25 Comment(0)
H
2

try const spanText = (await findByText('SPAN A')).parentNode.childNodes;

Hydroxy answered 27/10, 2020 at 12:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.