RegEx 可以与 React 测试库一起使用来检查类名吗?

rob*_*ear 7 reactjs react-testing-library

这是我的 React 测试库测试中的一行:

expect(queryByTestId('tile-sample-service')).toHaveClass('regularTile-0-2-24', 'btn', 'btn-outline-secondary');
Run Code Online (Sandbox Code Playgroud)

虽然它有效,但测试很脆弱,因为每次组件的结构发生变化时,我都需要返回并修复已更改的数字。

有没有一种方法可以toHaveClass与 RegEx 查询一起使用,或者是否有其他方法可以检查类是否存在但避免添加“0-2-24”之类的内容?

ilo*_*ett 12

是的,对于 JS 中的某些 CSS 生成的类名,有时数字后缀会发生变化。

像这样的东西应该有效:

const currentLinkAnchorEl = getByText(container, 'My Currently Active Link').closest('a');

expect(currentLinkAnchorEl.className).toMatch(/mySelectedActiveClassName/)
Run Code Online (Sandbox Code Playgroud)


Ale*_*lex 1

我认为这是不可能的toHaveClass(...classNames: string[]),但你可以使用Shallow Renderer,试试这个

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

    })
Run Code Online (Sandbox Code Playgroud)