Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can RegEx be used with React Testing Library to check classnames?

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" ?

like image 369
robertwerner_sf Avatar asked Mar 02 '23 21:03

robertwerner_sf


2 Answers

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/)
like image 107
ilovett Avatar answered Mar 12 '23 15:03

ilovett


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

    })
like image 29
Alex Avatar answered Mar 12 '23 16:03

Alex