首页 > 解决方案 > 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" ?

标签: reactjsreact-testing-library

解决方案


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

像这样的东西应该工作:

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

expect(currentLinkAnchorEl.className).toMatch(/mySelectedActiveClassName/)

推荐阅读