. Advertisement .
..3..
. Advertisement .
..4..
React is an important front-end language when it comes to simplicity and flexibility while working on a project. When you are writing tests for react components, the enzyme is a popular testing tool. With this testing tool, you can render components, find elements by className in React Testing Library, component display name, CSS selector, component constructor, and property.
The React Testing Library is built on top of the testing library DOM. If you are working on the project to find elements by className in React Testing Library, then you can find your answers here.
Take a look at how to find elements by className in React Testing Library
How to Find Elements by className in React Testing Library
As we have already discussed above about the React Testing Tool, we highlight the methods to use when finding elements by className
Using getElementsByClassName() Method
To find the className of elements, this method is used on the container. When we apply this method to the ‘container’ object, we can get the return once we render a component. Let’s have a look at the code
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);
});
Look at 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 also require to disable some of the listing rules as it is not the way React Testing Library is meant to be used. The docs state should avoid testing implementation details like the class name as users of the applications has no idea about it.
However, selecting the elements by the class name is the best solution.
Using the ‘findAllByText’ Method
In this case, you would like to test if an element has a particular class. For this, selecting an element by its text and checking for the class existence. With this method, you can select all the elements containing the text ‘box’. Let’s see the code
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 can pass a regular expression to the method.
Conclusion
To find elements by className in React Testing Library has been discussed in detail, and that too in a simpler way to help you understand the code and the method used. Hope you find the solution to get through the code you are working on!
Feel free to drop a message below if you find It useful and even comment below if you need any assistance.
I wish you Good Luck for Coding!
Leave a comment