CodePark/ questions / Testing Library queries
START PRACTICINGPRACTICE
Frontend question · Testing › Testing Library queries

Each row in an invoices table has a 'Delete' button, so screen.getByRole('button', { name: 'Delete' }) throws 'Found multiple elements'. What's the best fix to click the Delete button for invoice 42?

within(screen.getByRole('row', { name: /invoice 42/i })).getByRole('button', { name: 'Delete' })

The within option is best. within limits queries to one element, so you target the button the way a user would: the Delete button in invoice 42's row. The tempting getAllByRole(...)[3] option works, but it breaks when the row order changes. The queryByRole and findByRole options fail too. They also throw or reject when several elements match.