Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find element by id in react-testing-library

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'); 
like image 809
aks Avatar asked Oct 26 '18 07:10

aks


People also ask

How do I get by id in React testing library?

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');

How do you find the element by class name in React testing library?

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.

What is getByTestId?

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).


1 Answers

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'); 
like image 133
Liran H Avatar answered Oct 12 '22 07:10

Liran H