用Jest-Enzyme测试样式化的组件

dmr*_*tis 5 unit-testing reactjs jestjs enzyme styled-components

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

假设我的组件如下:

const myColor = '#111';

const Button = styled.button`
  background-color: ${myColor};
`;
Run Code Online (Sandbox Code Playgroud)

然后测试检查该'background-color'属性是否具有值'#111'

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

dmr*_*tis 5

toHaveStyleRule功能的玩笑风格的组件解决我的问题!

import 'jest-styled-components'

describe('<Button> component', () => {
  it('should have myColor', () => {
    const wrapper = mount(<Button />);
    expect(wrapper.find('Button')).toHaveStyleRule('background-color', myColor)
  });
});
Run Code Online (Sandbox Code Playgroud)