1

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
});

2 Answers 2

3

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');
});
Sign up to request clarification or add additional context in comments.

Comments

1

As @ThomasSquall mentioned toHaveClass accepts a list of classnames to test.

A more general approach for this (no matter which API you are using) is to use standard JS constructs in your unit tests.

For example you could do something like this:

['class-one', 'class-two'].forEach(className => {
   expect(myElement).toHaveClass(className)
})

3 Comments

Thanks, but I was hoping for a proper Jest solution not a JS workaround.
In that case @ThomasSquall's answer is what you are looking for
I know, gonna accept in a second.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.