I'm using react-testing-libarary to test my react application. For some reason, I need to be able to find the element by id
and not data-testid
. There is no way to achieve this in the documentation.
Is there a way to achieve this?
I've the rendered output as:
const dom = render(<App />);
I'm looking for something in line of:
const input = dom.getElemenById('firstinput'); //or const input = dom.getById('firstinput');
I found a way to do this. import App from './App'; import { render, queryByAttribute } from 'react-testing-library'; const getById = queryByAttribute. bind(null, 'id'); const dom = render(<App />); const table = getById(dom. container, 'directory-table');
To find elements by className in React testing library: Render a component and destructure the container object from the result. Use the getElementsByClassName() method on the container to find elements by class name.
getByTestId only when there isn't anything you cant easily latch onto from your UI. getByTestId: The user cannot see (or hear) these, so this is only recommended for cases where you can't match by role or text or it doesn't make sense (e.g. the text is dynamic).
I feel like none of the answers really gave a complete solution, so here it is:
const result = render(<SomeComponent />); const someElement = result.container.querySelector('#some-id');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With