如何使用 React 测试库获取共享相同文本的按钮?
How to get buttons that share the same text using React Testing Library?
我的组件有一个名称列表,每个名称旁边都有一个添加按钮
<h1>Select one of me!</h1>
<div>
<button>contrived</button>[I am already selected]
<button>example</button>
<button>beep</button> [I am already selected]
<button>boop</button>
</div>
<h1>Selected</h1>
<button>contrived</button>
<button>beep</button>
如果我想 select beep
或 contrived
在底部列表中,应该如何配置按钮以便我可以轻松找到它们而无需测试 ID 或使用我的当前结构的知识(即如果有更好的方法,我想避免获取父元素并使用 within
助手)。
在不使用显式测试 ID 或其他属性的情况下,您可以使用 getAllByText
查询来检索两者并使用您想要的那个。
const [firstBeep, secondBeep] = screen.getAllByText('beep')
这假设您了解它们在 DOM 中的排序,但不考虑结构本身。
我的组件有一个名称列表,每个名称旁边都有一个添加按钮
<h1>Select one of me!</h1>
<div>
<button>contrived</button>[I am already selected]
<button>example</button>
<button>beep</button> [I am already selected]
<button>boop</button>
</div>
<h1>Selected</h1>
<button>contrived</button>
<button>beep</button>
如果我想 select beep
或 contrived
在底部列表中,应该如何配置按钮以便我可以轻松找到它们而无需测试 ID 或使用我的当前结构的知识(即如果有更好的方法,我想避免获取父元素并使用 within
助手)。
在不使用显式测试 ID 或其他属性的情况下,您可以使用 getAllByText
查询来检索两者并使用您想要的那个。
const [firstBeep, secondBeep] = screen.getAllByText('beep')
这假设您了解它们在 DOM 中的排序,但不考虑结构本身。