Last updated: Apr 6, 2024
Reading time·2 min
To find elements by className in React testing library:
container
object from the result.getElementsByClassName()
method on the container to find elements
by class name.import {render} from '@testing-library/react'; import App from './App'; test('renders react component', () => { const {container} = render(<App />); // eslint-disable-next-line testing-library/no-container, testing-library/no-node-access const boxes = container.getElementsByClassName('box'); console.log(boxes.length); // 👉️ 2 expect(boxes.length).toBe(2); });
Here is the App
component from the example.
export default function App() { return ( <div> <div className="box">Box 1</div> <div className="box">Box 2</div> </div> ); }
We can use the getElementsByClassName
method on the container
object we get
after rendering a component.
// eslint-disable-next-line testing-library/no-container, testing-library/no-node-access const boxes = container.getElementsByClassName('box');
However, note that we had to disable some linting rules because that's not the way the React testing library is intended to be used.
The docs state that we should avoid testing implementation details (things the users of our application don't know about), e.g. class names.
If you need to find all elements by class name in React, click on the following article.
If you need to test if an element has a specific class, you can select the element by its text and check for the existence of the class.
import {render, screen} from '@testing-library/react'; import App from './App'; test('renders react component', async () => { render(<App />); const boxes = await screen.findAllByText(/box/i); expect(boxes[0]).toHaveClass('box'); expect(boxes[1]).toHaveClass('box'); });
We used the findAllByText
method to select all elements that contain the text
box
.
Notice that we are able to pass a regular expression to the method.
You can view the queries priority list of the React testing library in this section of their docs.
You can learn more about the related topics by checking out the following tutorials: