如果没有名称,如何在 React 测试库的 getByRole 中获取第二项?

我知道我可以在这里使用名称选项来选择第一项,但是如果没有分配名称,我该如何选择第二项呢?

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

      --------------------------------------------------
stack overflow How to get second item in getByRole in React Testing Library if there is no name?
原文答案

答案:

作者头像
作者头像

假设react组件呈现这样的东西

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

你可以这样做,但这只有在第二个按钮没有任何文本和属性名称时才有效

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