How to get buttons that share the same text using React Testing Library?

Viewed 383

The component I have has a list of names with an add button beside each

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

If I wanted to select beep or contrived in the bottom list, how should the buttons be configured so that I can easily find them without test-ids or using my knowledge of the current structure (i.e. I want to avoid getting the parent element and using the within helper if there's a better way).

1 Answers

Without using explicit test IDs or other attributes, you could use the getAllByText query to retrieve both and use the one you want.

const [firstBeep, secondBeep] = screen.getAllByText('beep')

This does assume you have knowledge about their ordering in the DOM, but doesn't take into account the structure itself.

Related