I am using React Testing Library and would like to assert that a particular dynamic class name is not present on my element.
MyEl.jsx
const MyEl = (someCondition = false, customClassName = '') => (
<div className={!!someCondition ? `my-custom-class-${customClassName}` : null}>
some content
</div>
);
I know that the toHaveClass matcher for Jest expects a proper String, but I thought I might be able to get away with doing an expect of a partial string instead...
it('Should not have custom class', () => {
render(<MyEl />);
const mainEl = screen.getByText('some content');
expect(mainEl).not.toHaveClass(expect.stringContaining('my-custom-class-'));
})
This gives me the error that it is expecting a full string.
Is there something similar to what I am trying to do that will actually work?
You can use expect.not.stringContaining(string)
expect.not.stringContaining(string)matches the received value if it is not a string or if it is a string that does not contain the exact expected string.
It is the inverse of
expect.stringContaining.
And, you can get the element's class content by el.className attribute.
index.tsx:
import React from 'react';
export const MyEl = ({ someCondition = false, customClassName = '' }) => (
<div className={!!someCondition ? `my-custom-class-${customClassName}` : ''}>some content</div>
);
index.test.tsx:
import { render, screen } from '@testing-library/react';
import React from 'react';
import { MyEl } from '.';
describe('71648378', () => {
it('Should not have custom class', () => {
render(<MyEl />);
const mainEl = screen.getByText('some content');
expect(mainEl.className).toEqual(expect.not.stringContaining('my-custom-class-'));
});
it('Should have custom class', () => {
render(<MyEl someCondition customClassName="abc" />);
const mainEl = screen.getByText('some content');
expect(mainEl.className).toEqual(expect.stringContaining('my-custom-class-'));
});
});
Test result:
PASS stackoverflow/71648378/index.test.tsx (9.36 s)
71648378
✓ Should not have custom class (23 ms)
✓ Should have custom class (2 ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 10.176 s, estimated 12 s