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)
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.
Most helpful comment
After looking at what
hasClassNamesandgetModifiedClassNameare doing, looks like I need to provide amodifierfor className as well?Is this the preferred way of testing something like this?