Test styled component with Jest-Enzyme
Asked Answered
I

2

14

How can I test if my styled-component has a specific CSS attribute-value pair?

Let's say my component is the following :

const myColor = '#111';

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

And the test checks that the 'background-color' attribute has the value '#111'.

The test runner is Jest and I use the testing utilities library Enzyme.

Individuation answered 4/1, 2019 at 10:24 Comment(0)
I
16

The toHaveStyleRule function of jest-styled-components solved my problem!

import 'jest-styled-components'

describe('<Button> component', () => {
  it('should have myColor', () => {
    const wrapper = mount(<Button />);
    expect(wrapper.find('Button')).toHaveStyleRule('background-color', myColor)
  });
});
Individuation answered 4/1, 2019 at 12:28 Comment(2)
what if a component with specificity hack needs to be tested, like that one const Button = styled.button' && { background-color: ${myColor}; }'; toHaveStyleRule doesn't work in this case for meSextillion
Found the solution: adding modifier: '&&', to the toHaveStyleRule method worked for me, like that: .toHaveStyleRule('background-color', myColor, { modifier: '&&' });Sextillion
B
0

Here is the way I follow to write the test case for styled component to test css, It might help and easy to write

import renderer from "react-test-renderer";

describe("Styled Components", () => {
  it("<Button  /> should have the correct styles", () => {
    const component = renderer.create(<Button />).toJSON();
    expect(component).toHaveStyleRule("background-color", myColor);
  });
});

Thank You

Billie answered 11/10, 2023 at 7:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.