Multiple Elements Found
Error message
TestingLibraryElementError: Found multiple elements with the role/text
Quick summary
The query found more than one element. getBy* queries must find exactly one match — use getAllBy* for multiple matches.
Why this happens
The component renders multiple elements matching the query.
The query is too broad (e.g., getByRole('button') with multiple buttons).
List rendering creates multiple elements with the same text.
Using getBy* where getAllBy* should be used.
Minimal example
test('click submit', () => {
render(<Form />);
// Multiple buttons exist
const button = screen.getByRole('button'); // error: found 3 buttons
});test('click submit', () => {
render(<Form />);
const button = screen.getByRole('button', { name: 'Submit' }); // specific
});Make the query more specific with a name option to match exactly one element.
How to diagnose
Use screen.debug() to see all rendered elements.
Count how many elements match the query.
Make the query more specific (e.g., add a name option: getByRole('button', { name: 'Submit' })).
Use getAllBy* if multiple matches are expected.
How to fix
Make the query more specific: getByRole('button', { name: 'Submit' }) instead of getByRole('button').
Use getAllByText/getAllByRole if multiple matches are expected.
Use within() to scope the query to a specific part of the DOM.
How to prevent
Make queries specific enough to match exactly one element.
Use getAllBy* when you expect multiple matches.
Use within(container) to narrow the search scope.
Related Resources
Related Glossary
Related Lessons
- React Testing
Testing React components.