How can i write a test using React Testing Library to check if hover changes the components style?

Viewed 3499

I am testing my application, and encountered a problem. When trying to test whether a row in my Dropdown component applies an effect on hover, I noticed I was not able to check elements for their background color, which I find odd.

Trying to use the jest-dom matcher "toHaveStyle()", the following is an example where I cannot for the life of me get it to work.

dropdown.test.tsx

test('Should contain clickable elements that change style when hovered', () => {
    const dropElement1 = screen.getByLabelText('testLabel1');
    expect(dropElement1).toHaveStyle('background: white');
});

Error

Error

I have also tried this by using 'background-color', by using the hex value (another interesting bug is that PrettyDom converts hex to RGB), or by adding ; to the declaration in toHaveStyle().

I am certain that the element is indeed white, and I can't understand what is going wrong. If my approach is bad practice and you have a better idea of how to check this, or you have a solution to my problem, please, let me know!

1 Answers

Your testing case can't find the dropElement1 styles because it's a drop-down menu and not opened since you just render the Dropdonw component.

You need to simulate a mouse hover or clicking action on the DropDown menu and then expect to have styles property for it.

import React from "react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { Dropdown } from "./Dropdown";

test('Should contain clickable elements that change style when hovered', () => {
    render(<Dropdown />);
    
    fireEvent.mouseEnter(screen.getByText('drop-down-btn'));
    
    await waitFor(() => screen.getByTestId('dropdown-menu'))

    expect(screen.getByLabelText('testLabel1')).toHaveStyle('background: white');
});

Note: as you have not posted the Dropdown component, I put some sample names for getting your toggles and drop-down menu. also, you can read about the mouse events on the react-testing-library. you can also use mouseOver but it depends on your drop-down menu implementation.

Related