Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get second item in getByRole in React Testing Library if there is no name?

I know I can use the name option to select the first item here, but how can I select the second item if there is no name assigned to it?

      --------------------------------------------------
      button:

      Name "Go":
      <button
        class="MuiButtonBase-root MuiButton-root MuiButton-contained MuiButton-containedPrimary"
        style="margin-left: 5px;"
        tabindex="0"
        type="button"
      />

      Name "":
      <div
        aria-haspopup="listbox"
        class="MuiSelect-root MuiSelect-select MuiSelect-selectMenu MuiSelect-outlined MuiInputBase-input MuiOutlinedInput-input"
        role="button"
        tabindex="0"
      />

      --------------------------------------------------
like image 473
jwhunt19 Avatar asked Jan 17 '26 18:01

jwhunt19


1 Answers

Use getAllByRole to get an array and then select the second element using eq:

screen.getAllByRole('button').eq(1)

https://testing-library.com/docs/dom-testing-library/cheatsheet/#queries

like image 75
Findlay Hannam Avatar answered Jan 20 '26 06:01

Findlay Hannam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!