"No style rules found on passed Component" 当使用 react-testing-library 对样式化组件的直接子组件进行单元测试时
"No style rules found on passed Component" when unit testing direct child of styled component using 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
这是我的组件的 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