Tips for testing CSS hover states using Enzyme in React

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');
    });

Answer №1

If you ever need to refer back, the fix for this issue involves utilizing the opts parameter within the toHaveStyleRule function.

To address this, make sure to implement the following code:

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

For further information, you can visit the documentation here: https://github.com/styled-components/jest-styled-components#tohavestylerule

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display a div using Jquery depending on the visibility and checked value of another div

Trying to toggle the visibility of a div based on another div's input has proven to be quite challenging in this scenario. Here is the HTML setup: <div id="main-question"> <div class="form-group"> <div class="form-radios"> ...

CSS - Issue with dropdown sub-menu alignment despite using absolute positioning in relation to parent button

Title fairly explains it all. I'm having trouble getting my dropdown submenus to align perfectly with the bottom of the parent list item element. The list item has a relative position, while the submenu has an absolute position. I've attempted ...

Is your Chrome DevTools changing CSS Link files to "Constructed Stylesheet" after you edit the CSS using Inspect Element? Find out how to fix this issue!

This issue relates to CSS files that are initially not identified as constructed stylesheets but end up being displayed as such after editing, rendering the file inaccessible. Specifically in Google Chrome DevTools (last observed in Chrome 86): Whenever ...

When working with create-react-app and TypeScript, you may encounter an error stating: "JSX expressions in 'file_name.tsx' must

After setting up a React project with TypeScript using the CLI command create-react-app client --typescript, I encountered a compilation error when running npm start: ./src/App.js Line 26:13: 'React' must be in scope when using JSX react/r ...

Creating a professional HTML/CSS signature for optimal performance in Outlook 2016

For my email signature, I currently have an HTML coded design that includes a 400x415 dashed line with specific color specifications. However, Outlook Express 2016 is unable to display this element properly. Despite using inline CSS, it appears that CSS d ...

"Encountering a Challenge with Setting Up Forms on

I've recently started learning to code and I'm facing an issue with my form appearing stretched out. You can view it here: I initially thought it was due to margins, so I increased them. Then, I tried adjusting the width to 50%, but that didn&ap ...

Discovering the best method for accessing CSS classes locally within an Angular component

In order to style a 3rd-party component with custom styles, I need to access the dynamically generated css classname from within an angular component. Angular applies transformations to local css classnames for scoping purposes. However, when trying to st ...

Do we need to include all variables used in useEffect within the dependencies array?

I understand how dependencies work in useEffect. However, I have a unique scenario where I need to conditionally process flow based on a prop value without watching its changes. This poses a challenge because omitting the prop from the dependencies array t ...

Utilize React to transform PDF files into PNG images and seamlessly upload them to Cloudinary

Currently, I am utilizing react typescript and looking to select a PDF file, transform the PDF into an image, and then upload the final image onto Cloudinary. Although I have a service set up for uploading images in my Cloudinary media library, I am unsu ...

Combining SlateJS with Redux

I need to store the value of a SlateJS editor in redux instead of state, but when I modify the hasLinks method, I encounter an immediate crash with the error message: TypeError: Cannot read property 'inlines' of undefined Modified Editor&apos ...

Switch from using `widthWidth` to `useWidth` in MUI v5 ReactJS

Currently, I am in the process of updating a project that utilizes MUI as the UI Library for my React application. I have started migrating to version 5 today, and one issue I've encountered is related to all functional components wrapped by withWidth ...

"Unlocking the full potential of Typescript and Redux: Streamlining the use of 'connect' without the need to

I am facing some challenges with typescript and redux-thunk actions. The issue arises when my components heavily rely on react-redux connect to bind action creators. The problem occurs when I create the interface for these redux actions within the compone ...

Error: client.watchQuery() cannot be invoked while fetchPolicy is set to "standby"

After cloning my project on an Ubuntu machine, I ran yarn install followed by yarn start. Unfortunately, it resulted in the error mentioned above. Strangely, the same process works perfectly on my Windows machine. ...

Image Appears Oversized on Mobile Due to Responsiveness

Attempting to make this landing page responsive has been quite challenging. Unfortunately, on mobile devices the image extends beyond the width of the screen when in portrait mode, requiring users to scroll to view the images and form. My expertise lies in ...

Using the `map()` method in React to filter elements based on their index and only running the filter if the index meets a certain

I have a list that needs to be iterated through based on its index. The filtering criteria are as follows: if index == 0 if index is above 0 and below half of the array's length if index is above half of the array's length The current code I&a ...

What is the reason for the lang parameter not being inherited by getStaticProps from getStaticPaths?

getStaticPaths method: const fetchEvents = async () => { let eventData = await fetch(`${baseURL}getEvents2`, { method: "post", }); let events = await eventData.json(); const paths = ["hu", "en"].flatMap((lang) = ...

The error message "Unable to execute n.toLowerCase as a function when working with JSX" is

I'm attempting to utilize span tags in order to display project numbers within a dropdown list, but I'm encountering an error. The problematic code snippet is as follows. You can find my sandbox link here import React from "react"; impo ...

A guide to dynamically changing avatar colors in ReactJS when clicked

An issue arose with my Material UI avatar as it takes colors (pink/green) from styles. The problem occurs when I need to change the color from pink to green based on an onclick event. I attempted to store the color name in state, but encountered difficulti ...

Implementing a feature in MUI for editing and deleting multiple rows with a single save button in a MUI DataGrid

We are currently working on customizing the MUI datagrid to include bulk edit and delete functionality. Despite our efforts, we have not been able to find any references or documentation regarding bulk crud operations. We are open to upgrading to the pro ...

Is there a way to verify if the overflow of an element with a width of 100% has occurred?

Here is the structure I am working with: <div class="card"> <div class="container"> <slot /> </div> </div> The Card element has a fixed width of 33rem. The container within it spans 100% of ...