【问题标题】:Test styled component with Jest-Enzyme使用 Jest-Enzyme 测试样式组件
【发布时间】:2019-05-30 21:56:23
【问题描述】:

如何测试我的styled-component 是否具有特定的 CSS 属性值对?

假设我的组件如下:

const myColor = '#111';

const Button = styled.button`
  background-color: ${myColor};
`;

并且测试检查'background-color' 属性的值是否为'#111'

测试运行器是 Jest,我使用测试实用程序库 Enzyme

【问题讨论】:

    标签: reactjs unit-testing jestjs enzyme styled-components


    【解决方案1】:

    jest-styled-componentstoHaveStyleRule 函数解决了我的问题!

    import 'jest-styled-components'
    
    describe('<Button> component', () => {
      it('should have myColor', () => {
        const wrapper = mount(<Button />);
        expect(wrapper.find('Button')).toHaveStyleRule('background-color', myColor)
      });
    });
    

    【讨论】:

    • 如果需要测试具有特异性 hack 的组件怎么办,比如 const Button = styled.button' &amp;&amp; { background-color: ${myColor}; }'; toHaveStyleRule 在这种情况下对我不起作用
    • 找到解决方案:将modifier: '&amp;&amp;', 添加到toHaveStyleRule 方法对我有用,就像这样:.toHaveStyleRule('background-color', myColor, { modifier: '&amp;&amp;' });
    猜你喜欢
    • 2017-02-12
    • 2018-08-20
    • 2019-09-24
    • 2020-01-27
    • 2021-01-08
    • 2020-05-10
    • 2018-08-30
    • 1970-01-01
    • 2019-08-23
    相关资源
    最近更新 更多