我是使用 Enzyme 和 Jest 进行 React 测试的新手,我有这个场景要测试:
当悬停 ParentDiv 时,Child div 应将样式更改为 background-color: green
和 display: block
.
但在测试中,模拟后mouseenter
事件,风格没有改变,他们仍然background-color: red
和 display: none
这是一个基于类的组件
const Child = styled.div`
background-color: red;
display: none;
`;
const ParentDiv = styled.div`
&:hover {
${Child} {
background-color: green;
display: block;
}
}
`;
<ParentDiv>
<Child>
<p>{text}</p>
</Child>
</ParentDiv>
测试.js
it('Hover over ParentDiv should display the child', () => {
const Wrapper = mount(<MyComponent >);
const parent = Wrapper.find('ParentDiv');
const child = Wrapper.find('child');
expect(child).toHaveStyleRule('display', 'none');
expect(child).toHaveStyleRule('background-color', 'red');
parent.simulate('mouseenter');
// next two lines not working
// expect(child).toHaveStyleRule('display', 'block'); // expected display: block but received display: none
// expect(child).toHaveStyleRule('background-color', 'green');
});
最佳答案
如果有人来看,解决方案是使用 opts
toHaveStyleRule
中的参数.
所以你需要使用这个:expect(child).toHaveStyleRule('display', 'block', { modifier: ':hover' });
这是文档的链接:https://github.com/styled-components/jest-styled-components#tohavestylerule
关于css - 如何在 Enzyme 中测试 CSS 悬停 - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60816035/