Recently starting with React testing using Enzyme and Jest, I encountered a scenario that needs to be tested:
When the mouse hovers over the ParentDiv, the Child div is supposed to change its style to background-color: green
and display: block
. However, during testing, even after simulating the mouseenter
event, the styles remain as background-color: red
and display: none
.
This component is based on classes.
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('Hovering over ParentDiv should make the child visible', () => {
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');
// The following two lines are not working
// expect(child).toHaveStyleRule('display', 'block'); // expected display: block but received display: none
// expect(child).toHaveStyleRule('background-color', 'green');
});