我正在测试我的应用程序,但遇到了问题。在尝试测试我的 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() 中的声明。
我确定元素确实是白色的,我无法理解出了什么问题。如果我的方法是不好的做法,并且您对如何检查有更好的想法,或者您有解决我的问题的方法,请告诉我!
最佳答案
您的测试用例找不到 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
但这取决于您的下拉菜单实现。
关于reactjs - 如何使用 React 测试库编写测试来检查悬停是否更改了组件样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69467223/