getBy query fails in React Testing Library because several elements match
TestingLibraryElementError: Found multiple elementsShort answer
getBy and queryBy throw when more than one element matches, and findBy rejects. Narrow the query with the name option of getByRole or by scoping with within. If several matches are expected, use getAllBy. If you see duplicates you did not render, earlier tests left DOM behind: check automatic cleanup.
Fix it fast
1Find out which cause you have
Read which elements the error lists, then print the DOM to see why there are several.
screen.debug()2Match what you see, then jump to its fix
- 1
The error lists several elements of the same role or text, all legitimately renderedThe query is too broad for the pageFix - 2
A list, table or repeated card renders by designThe match is expected to be several elementsFix - 3
Both a nav link and a heading have the same labelThe same text appears in two regions of the pageFix - 4
Duplicates appear only when several tests run, and the single test passes aloneEarlier tests left their render in the documentFix
- 1
What does the error look like?
TestingLibraryElementError: Found multiple elements
Cause 1 of 4
The query is too broad for the page
1Check
Per the Testing Library docs, getBy throws a descriptive error when more than one element matches.
screen.getAllByRole('button').map(b => b.textContent)2Fix
Add the name option so the role query matches one accessible name.
screen.getByRole('button', { name: 'Close' })3Verify
Re-run the test.
npx jest path/to/file.test.jsxConfirmed by testing-library.com
Cause 2 of 4
The match is expected to be several elements
1Check
The docs provide getAllBy, queryAllBy and findAllBy for several matches. queryAllBy returns an empty array when there is none.
screen.getAllByRole('listitem')2Fix
Use getAllBy and assert on the array.
const items = screen.getAllByRole('listitem');
expect(items).toHaveLength(3);3Verify
Run the test; the assertion on length passes.
npx jest path/to/file.test.jsxConfirmed by testing-library.com
Cause 3 of 4
The same text appears in two regions of the page
1Check
within limits a query to the children of one element, and screen is bound to document.body.
screen.debug()2Fix
Scope the query with within to the region you mean.
import { within } from '@testing-library/react';
const nav = screen.getByRole('navigation');
within(nav).getByRole('link', { name: 'Home' });3Verify
Run the test.
npx jest path/to/file.test.jsxConfirmed by testing-library.com
Cause 4 of 4
Earlier tests left their render in the document
1Check
RTL's setup docs say cleanup runs after each test automatically only when the test framework provides a global afterEach.
npx jest path/to/file.test.jsx -t 'test name'2Fix
Make sure the framework exposes afterEach globally (for Vitest set globals: true), or call cleanup yourself in afterEach. Also check RTL_SKIP_AUTO_CLEANUP is not set.
import { cleanup } from '@testing-library/react';
afterEach(cleanup);3Verify
Run the whole file and confirm no duplicates.
npx jest path/to/file.test.jsxConfirmed by testing-library.com
How do I stop it coming back?
- Prefer getByRole with name; it matches how users find elements.
- Use within for repeated regions.
- Leave automatic cleanup on.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- TaskvareA task and project-management suite: React on the web, Flutter on mobile, TypeScript underneath.
Related fixes
Web apps
Module not found for antd/dist/antd.less after upgrading to Ant Design 5
Module not found: Error: Can't resolve 'antd/dist/antd.less'
Ant Design 5 dropped Less and the bundled CSS file for CSS-in-JS, so antd/dist/antd.less no longer exists.
3 causes, each with a fixWeb apps
Astro Code component fails inside a React component
Astro components cannot be rendered directly via function call
Astro components such as Code only exist on the server and render static HTML.
2 causes, each with a fixWeb apps
React shows Attempted import error when importing a component or function
Attempted import error:
The build found the file but not the name you asked for.
2 causes, each with a fixWeb apps
How to catch and handle a 422 from Axios in a Redux thunk
action.error.message is 'Rejected' and action.payload is undefined
A 422 means the server read the request but cannot process its content, so repeating it unchanged fails again.
4 causes, each with a fixWeb apps
axios gets 429 Too Many Requests from a React app
429 (Too Many Requests)
A 429 comes from the server or an API gateway, not from axios: your client sent too many requests in a window.
4 causes, each with a fixWeb apps
Axios request is not cancelled when a React component unmounts
A cancelled request is logged as an error in the catch block
Axios cancels a request when you pass it an AbortSignal and later call abort() on its controller.
4 causes, each with a fix