3
votes

I am new To React testing with Enzyme and Jest, and I have this scenario to test:

When hover the ParentDiv, The Child div should change style to background-color: green and display: block. But in testing, after simulate mouseenter event, none of the style is changed, they still background-color: red and display: none

This is a Class-based component

const Child = styled.div`
    background-color: red;
    display: none;
`;

const ParentDiv = styled.div`
    &:hover {
        ${Child} {
            background-color: green;
            display: block;
        }
    }
`;

<ParentDiv>
  <Child>
    <p>{text}</p>
  </Child>
</ParentDiv>   

Test.js

it('Hover over ParentDiv should display the child', () => {
        const Wrapper = mount(<MyComponent >);
        const parent = Wrapper.find('ParentDiv');
        const child = Wrapper.find('child');

        expect(child).toHaveStyleRule('display', 'none');
        expect(child).toHaveStyleRule('background-color', 'red');
        parent.simulate('mouseenter');
        // next two lines not working
        // expect(child).toHaveStyleRule('display', 'block');  // expected display: block but received display: none
        // expect(child).toHaveStyleRule('background-color', 'green');
    });
1
Are you using mount or shallow to render the component? Is it class based or functional? - Muhammad Haseeb
I updated my question - asmaa
have you found solution on this? @asmaa - muhsalaa
Unfortunately no! - asmaa
i also struggle to find solution for this - muhsalaa

1 Answers

2
votes

In case anyone comes looking, the solution for this is to use the opts parameter in toHaveStyleRule.

so you need to use this:

expect(child).toHaveStyleRule('display', 'block', { modifier: ':hover' });

Here is a link to the docs: https://github.com/styled-components/jest-styled-components#tohavestylerule