Jest-styled-components: toHaveStyleRule and "custom" classNames

Created on 16 Sep 2018  路  3Comments  路  Source: styled-components/jest-styled-components

If you manually provide a className to a styled component, shouldn't toHaveStyleRule return the resulting CSS from that class?

Say I have a button component like so

const Button = styled.button`
  background-color: blue;

  &.focus {
    background-color: red;
  }
`;

If I were to mount and test that component by giving it a className of focus, should I not expect the background-color to be red?

const wrapper = mount(<Button className="focus">I am a button!</Button>);
expect(wrapper).toHaveStyleRule('background-color', 'red');

Instead, it's still returning blue as the background-color. I know I can pass focus or whatever as a prop and conditionally change the CSS but I was wondering why the above doesn't work.

CodeSandbox link showing the issue: https://codesandbox.io/s/0m7qz6l52n (See the Tests tab on the bottom. The file in question is index.test.js)

Most helpful comment

After looking at what hasClassNames and getModifiedClassName are doing, looks like I need to provide a modifier for className as well?

const wrapper = mount(<Button className="focus">I am a button!</Button>);

expect(wrapper).toHaveStyleRule('background-color', 'red', {
  modifier: '&.focus',
});

Is this the preferred way of testing something like this?

All 3 comments

After looking at what hasClassNames and getModifiedClassName are doing, looks like I need to provide a modifier for className as well?

const wrapper = mount(<Button className="focus">I am a button!</Button>);

expect(wrapper).toHaveStyleRule('background-color', 'red', {
  modifier: '&.focus',
});

Is this the preferred way of testing something like this?

Hi @sumanbh,
yes, you identified the correct solution.

Any "child" within your style rules is a modifier and so the modifier option should be used with toHaveStyleRule.

Thanks @sumanbh for opening the issue, and searching for a solution.
Thank you very much @santino for providing more information.

Was this page helpful?
0 / 5 - 0 ratings