Find elements by className in React Testing Library

avatar
Borislav Hadzhiev

Last updated: Apr 6, 2024
2 min

banner

# 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.
App.test.js
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); });
The code for this article is available on GitHub

Here is the App component from the example.

App.js
export default function App() { return ( <div> <div className="box">Box 1</div> <div className="box">Box 2</div> </div> ); }

find elements by classname using react testing library

We can use the getElementsByClassName method on the container object we get after rendering a component.

App.test.js
// 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.

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 find all elements by class name in React, click on the following article.

# Testing if an element has a specific class

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.

App.js
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'); });

testing if element has specific class

The code for this article is available on GitHub

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.