简体   繁体   中英

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

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

    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM