"No style rules found on passed Component" 当使用 react-testing-library 对样式化组件进行直接子级的单元测试时



这是我的组件的样式li

const Tab = styled.li`
margin: 0px 60px;
color: black;
& > button {
border: none;
padding: 28px 0px;
font-weight: 600px;
}
`;

下面是失败的单元测试:

const tabItems = [
{
label: 'Test 1',
id: 'tab1',
},
{
label: 'Test 2',
id: 'tab2',
},
];
describe('Tabs styling tests', () => {
afterEach(cleanup);
it('should have font-weight 600', async () => {
const { getByText } = render(<Tabs tabItems={tabItems} selected="test1" />);
expect(getByText('Test 1')).toHaveStyleRule('font-weight', '600');
});
});

我正在为任何试图为该按钮测试的css样式获取No style rules found on passed Component

测试通过了所测试的任何.parentElement样式
例如,expect(getByText('Test 1').parentElement).toHaveStyleRule('color', 'black');运行良好。

如何测试样式化组件的直接子级?

最终找到了如何实现这一点:

it('should have font-weight 600', async () => {
const { getByText } = render(<Tabs tabItems={tabItems} selected="test1" />);
expect(getByText('Test 1').parentElement).toHaveStyleRule(
'font-weight', 
'600',
{ modifier: css`> button` }
);
});

来源:https://github.com/styled-components/jest-styled-components/blob/master/README.md#tohavestylerule

最新更新