Sometimes, we want to test a className with the Jest and React testing library.
In this article, we’ll look at how to test a className with the Jest and React testing library.
How to test a className with the Jest and React testing library?
To test a className with the Jest and React testing library, we can check if any element with the given class name exists with getElementsByClassName.
For instance, we write
it("Renders with a className equal to the variant", () => {
const { container } = render(<Button variant="default" />);
expect(container.getElementsByClassName("default").length).toBe(1);
});
to call render to render the Button component.
Then we get the container element and call getElementsByClassName with the class name to check if any element with class name default exists in the container element.
We check if the length is bigger than 0 to see if any element with the class name exists.
Conclusion
To test a className with the Jest and React testing library, we can check if any element with the given class name exists with getElementsByClassName.