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

Viewed 1060

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"
      />

      --------------------------------------------------
1 Answers

assuming the react component renders something like this

<div className="App">
  <button>first</button>
  <div role="button"></div>
  <button>third</button>
</div>
    

you can do like this, but this will only work if the second button doesn't have any text and attribute name to it

  it("check if second button content is empty",() => {
    render(<App />);
    const secondButton = screen.getByRole('button', {name: ''});
    expect(secondButton).toHaveTextContent('')
  });
Related