我知道我可以使用名称选项来选择这里的第一个项目,但是如果没有为其分配名称,我如何选择第二个项目?
--------------------------------------------------
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"
/>
--------------------------------------------------
使用
getAllByRole
获取数组,然后使用 eq
: 选择第二个元素
screen.getAllByRole('button').eq(1)
https://testing-library.com/docs/dom-testing-library/cheatsheet/#queries
假设反应组件呈现类似这样的东西
<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('')
});