React Testing Library cannot find an element by its data-testid
Unable to find the element with data-testidShort answer
getByTestId looks only at the DOM that exists right now, and only at the attribute named data-testid. It fails when the element appears later (use findBy), when the project changed testIdAttribute, or when the component never rendered because a provider is missing. Print the DOM with screen.debug() to see which one.
Fix it fast
1Find out which cause you have
Print what was rendered at the moment the query fails. The output shows if the element is missing, late or named differently.
import { screen } from '@testing-library/react'; screen.debug();2Match what you see, then jump to its fix
- 1
The id is in the component, and the DOM printed by screen.debug() shows a loading stateThe element appears after an async updateFix - 2
The markup printed by screen.debug() has your id on an attribute that is not data-testidThe project uses a different test id attributeFix - 3
screen.debug() prints an empty body or an error boundary instead of your componentThe component rendered without its providersFix - 4
The test fails while checking that an element disappearedThe assertion expects the element to be goneFix
- 1
What does the error look like?
Unable to find the element with data-testid
Cause 1 of 4
The element appears after an async update
1Check
getBy queries throw at once when nothing matches. findBy queries retry until a timeout, 1000 ms by default.
grep -rn "getByTestId" src --include=*.test.*2Fix
Await a findBy query for content that arrives after a fetch or a timer.
const row = await screen.findByTestId('user-row');
expect(row).toBeInTheDocument();3Verify
Run the test. If the data takes longer than the default, pass a larger timeout as the last argument.
npx jest
# slower data: await screen.findByTestId('user-row', {}, { timeout: 3000 })Confirmed by testing-library.com
Cause 2 of 4
The project uses a different test id attribute
1Check
getByTestId matches the attribute set by testIdAttribute, which defaults to data-testid. A setup file may have changed it.
grep -rn "testIdAttribute" . --include=*.js --include=*.ts --include=*.tsx --exclude-dir=node_modules2Fix
Either use the attribute the project configured, or set the configuration to match your markup.
// setup-tests.js
import { configure } from '@testing-library/react';
configure({ testIdAttribute: 'data-test' });3Verify
Run the tests again.
npx jestConfirmed by testing-library.com
Cause 3 of 4
The component rendered without its providers
1Check
A component that reads Redux or router context cannot render without a provider, so none of its test ids ever reach the DOM.
grep -rn "useSelector\|useDispatch\|useNavigate" src2Fix
Render through a wrapper that supplies the providers. A custom render function keeps this in one place.
const customRender = (ui, options) =>
render(ui, { wrapper: AllTheProviders, ...options });3Verify
Run the test and check that screen.debug() now shows the component.
npx jestConfirmed by testing-library.com
Cause 4 of 4
The assertion expects the element to be gone
1Check
getBy throws when nothing matches, so using it to assert absence fails by design.
grep -rn "not.toBeInTheDocument" src2Fix
Use queryBy, which returns null, for absence. For an element that is removed later, use waitForElementToBeRemoved.
expect(screen.queryByTestId('spinner')).not.toBeInTheDocument();3Verify
Run the test.
npx jestConfirmed by testing-library.com
How do I stop it coming back?
- Prefer queries by role or text. The docs list test ids as the last option, for cases where nothing else fits.
- Use findBy for anything that arrives after a request, and queryBy for absence.
- Keep one custom render with all providers and use it in every test.
- If a long DOM print is cut off, raise DEBUG_PRINT_LIMIT, which defaults to 7000 characters.
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
A React test warns that a state update was not wrapped in act()
Warning: The current testing environment is not configured to support act(...)
The warning means React state changed while your test was not waiting for it.
4 causes, each with a fixWeb 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 fix