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

1

8

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!

Yellowhammer answered 6/10, 2021 at 14:1 Comment(1)
Could you please provide the code for the component under test?Riedel
D
3

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

You need to simulate a mouse hover or clicking action on the DropDown menu and then expect to have a 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', async () => {
    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.

Despatch answered 12/10, 2021 at 9:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.