【问题标题】:How can i write a test using React Testing Library to check if hover changes the components style?我如何使用 React 测试库编写测试来检查悬停是否改变了组件样式?
【发布时间】:2021-10-12 17:25:43
【问题描述】:

我正在测试我的应用程序,但遇到了问题。在尝试测试 Dropdown 组件中的一行是否对悬停应用效果时,我注意到我无法检查元素的背景颜色,我觉得这很奇怪。

尝试使用 jest-dom 匹配器“toHaveStyle()”,以下是我一生无法让它工作的示例。

dropdown.test.tsx

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

错误

我也尝试过使用“背景颜色”、使用十六进制值(另一个有趣的错误是 PrettyDom 将十六进制转换为 RGB)或添加 ; toHaveStyle() 中的声明。

我确定元素确实是白色的,但我不明白出了什么问题。如果我的方法是不好的做法,并且您对如何检查有更好的想法,或者您有解决我的问题的方法,请告诉我!

【问题讨论】:

  • 能否提供被测组件的代码?

标签: reactjs unit-testing jestjs react-testing-library jest-dom


【解决方案1】:

您的测试用例找不到dropElement1 样式,因为它是一个下拉菜单,并且由于您只是渲染Dropdonw 组件而未打开。

您需要在DropDown 菜单上模拟鼠标悬停单击 操作,然后期望它具有样式属性。

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

注意:由于您尚未发布 Dropdown 组件,因此我提供了一些示例名称以获取您的切换和下拉菜单。此外,您可以在react-testing-library 上阅读有关鼠标事件的信息。您也可以使用mouseOver,但这取决于您的下拉菜单实现。

【讨论】:

    猜你喜欢
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 2021-09-25
    • 2010-11-05
    • 1970-01-01
    相关资源
    最近更新 更多