css - 如何在 Enzyme 中测试 CSS 悬停 - React

标签 css reactjs testing jestjs enzyme

我是使用 Enzyme 和 Jest 进行 React 测试的新手,我有这个场景要测试:

当悬停 ParentDiv 时,Child div 应将样式更改为 background-color: greendisplay: block .
但在测试中,模拟后mouseenter事件,风格没有改变,他们仍然background-color: reddisplay: 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/

相关文章:

C++:如何为模板类创建小型速度测试?

html - 如果 type=text 和 type=submit 的字体大小不同,则搜索形式难看的对齐方式

javascript - 如何仅使用 jquery 一次随机化动画

node.js - 使用 React 和 Node 进行 Firebase 身份验证

javascript - ReactJS - 使用 axios 响应抛出提交错误

javascript - 如何实现配置文件以替换 node.js Web App 中的文字值

javascript - 如何找到真正的DIV高度?

javascript - 具有动态填充和元素计数的 Flexbox 未正确调整大小

javascript - 如何获得分配给删除功能的正确 ID

java - 无法为我的 void 方法编写 Mockito 测试用例