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