我正在使用tippy库来处理我的应用程序中的工具提示。现在,我想测试当组件悬停在元素上时,组件是否显示工具提示内容。tippy库表示工具提示是由mouseEnter或focus事件触发的。
在测试它时,我使用fireEvent.mouseEnter()事件触发工具提示。它工作得很好,可以通过。但是当我使用userEvent.hover()的时候,它就没用了。userEvent.hover() 不支持 mouserEnter 事件吗?或者帮助我理解为什么在这里不起作用。
注意:fireEvent.mouseOver()在这里不工作。
我知道tippy已经被测试过了。我只是好奇为什么它不与userEvent.hover()一起工作。
以下是设计的/可复制的代码。CodeSandbox
import React from "react";
import Tippy from "@tippyjs/react";
const App = () => (
<Tippy content={<span>Tooltip</span>}>
<button>My button</button>
</Tippy>
);
export default App;import React from "react";
import { fireEvent, render, screen } from "@testing-library/react";
import "@testing-library/jest-dom";
import user from "@testing-library/user-event";
import App from "./App";
test("first", async () => {
render(<App />);
const button = screen.getByRole("button", { name: /my button/i });
expect(button).toBeInTheDocument();
user.hover(button);
expect(await screen.findByText(/tooltip/i)).toBeInTheDocument();
screen.debug();
});
test("second", async () => {
render(<App />);
const button = screen.getByRole("button", { name: /my button/i });
expect(button).toBeInTheDocument();
fireEvent.mouseEnter(button);
expect(screen.getByText(/tooltip/i)).toBeInTheDocument();
screen.debug();
});发布于 2022-12-03 19:55:13
userEvent.hover()函数模拟悬停事件,方法是触发一个mouseEnter事件,然后在短时间延迟后触发一个mouseLeave事件。这意味着,如果工具提示仅由mouseEnter事件触发,则它将在使用userEvent.hover()时迅速出现并消失。
相反,fireEvent.mouseEnter()函数只触发一个mouseEnter事件,该事件将触发工具提示的出现,而不会立即消失。
解决此问题的一个解决方案是更改触发Tippy组件中工具提示的事件。例如,您可以在mouseEnter事件和焦点事件上触发工具提示:
<Tippy content={<span>Tooltip</span>} trigger={['mouseEnter', 'focus']}>
<button>My button</button>
</Tippy>这样,当使用userEvent.hover()时,mouseEnter事件将触发工具提示的出现,而后续的mouseLeave事件不会导致它消失,因为它也是在焦点上触发的。
或者,您可以在测试中使用fireEvent.mouseEnter()而不是userEvent.hover()来触发工具提示。
发布于 2022-12-01 20:57:22
测试库中的user.hover()函数是焦点和mouseEnter事件的组合。但是,您只使用侦听mouseEnter事件的Tippy库,这就是为什么在这种情况下user.hover()不能工作的原因。
您可以修改提示库,以侦听焦点事件。
下面是一个示例,说明如何修改Tippy库以侦听焦点事件:
const App = () => (
<Tippy content={<span>Tooltip</span>} trigger="focus">
<button>My button</button>
</Tippy>
);这样,user.hover()函数将按预期工作。您还可以使用触发器支柱来指定哪些事件应该触发工具提示,以便在需要时可以组合多个事件。
我希望这能帮到你!如果你还有其他问题,请告诉我。
发布于 2022-12-03 18:51:22
userEvent.hover()方法通过依次触发元素上的mouseover和mouseout事件来模拟用户在元素上盘旋的过程。在您的代码中,您使用的是Tippy,根据其文档,这个库是由mouseEnter事件触发的。
由于userEvent.hover()方法不触发mouseEnter事件,所以不能使用它来触发tooltip。相反,您可以使用fireEvent.mouseEnter()方法(它在指定的元素上触发一个mouseEnter事件)来测试提示工具提示。
下面是使用fireEvent.mouseEnter()测试提示的测试代码的更新版本:
test("second", async () => {
render(<App />);
const button = screen.getByRole("button", { name: /my button/i });
expect(button).toBeInTheDocument();
fireEvent.mouseEnter(button);
expect(screen.getByText(/tooltip/i)).toBeInTheDocument();
screen.debug();
});https://stackoverflow.com/questions/74506809
复制相似问题