Here's a line from one of my React Testing Library tests:
expect(queryByTestId('tile-sample-service')).toHaveClass('regularTile-0-2-24', 'btn', 'btn-outline-secondary');
While it works, the test is fragile because every time the structure of the component changes, I need to go back and fix the numbers, which have changed.
Is there a way to use toHaveClass
with RegEx queries or is there some other way to check if classes are present but avoid having to add things like "0-2-24" ?
Yeah for some CSS in JS generated class names sometimes the number suffix changes.
Something like this should work:
const currentLinkAnchorEl = getByText(container, 'My Currently Active Link').closest('a');
expect(currentLinkAnchorEl.className).toMatch(/mySelectedActiveClassName/)
I think it's not possible with toHaveClass(...classNames: string[])
,but you can use Shallow Renderer
,try this one
import ShallowRenderer from 'react-test-renderer/shallow';
it('match claas name', () => {
const renderer = new ShallowRenderer();
renderer.render(<Component />);
expect(renderer.getRenderOutput().props.className).toMatch(/button/i);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With