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
});
CodePudding user response:
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');
});
CodePudding user response:
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)
})