Find elements by className in React Testing Library


Borislav Hadzhiev

Last updated: Apr 19, 2022


Photo from Unsplash

Find elements by className in React Testing Library #

To find elements by className in React testing library:

  1. Render a component and destructure the container object from the result.
  2. Use the 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.

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.

This might not apply to your use case and selecting elements by class name might be the best solution depending on what you need to do.

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.