Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I test for multiple classes at once using React Testing Library?

I want to check whether a DOM element has some specific classes or not. I know I can do this:

test('My element has correct classes assigned', () => {
    const myElement = screen.queryByText('This is my element');

    expect(myElement).toHaveClass('class-one');
    expect(myElement).toHaveClass('class-two');
});

I wonder if something like the following is possible too because my code is getting quite repetitive…

test('My element has correct classes assigned', () => {
    const myElement = screen.queryByText('This is my element');

    expect(myElement).toHaveClasses(['class-one', 'class-two']); // pseudo-code
});

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can easily achieve that by simply passing multiple classes to the toHaveClass method as an array or comma-separated values.

Example with an array:

test('My element has correct classes assigned', () => {
    const myElement = screen.queryByText('This is my element');

    expect(myElement).toHaveClass(['class-one', 'class-two']);
});

Example with comma-separate values:

test('My element has correct classes assigned', () => {
    const myElement = screen.queryByText('This is my element');

    expect(myElement).toHaveClass('class-one', 'class-two');
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading