Tra*_*gar 6 material-ui react-testing-library
我正在尝试在我的 React 应用程序上测试 Info HOC:
const InfoHOC = (HocComponent) => ({ message }) => (
<>
<Tooltip title={message}>
<InfoIcon />
</Tooltip>
{HocComponent}
</>
);
export default InfoHOC;Run Code Online (Sandbox Code Playgroud)
我已经简化了。但由于它使用 Material ui Tooltip 组件,我无法测试鼠标悬停时是否显示消息...
it('should display info message on <div /> mouseover', () => {
const Component = InfoHoc(<div>jest div</div>)({ message: 'jest infoHoc message' });
const { getByTitle, getByDisplayValue } = render(Component);
const icon = getByTitle('jest infoHoc message');
act(() => {
fireEvent(
icon,
new MouseEvent('mouseover', {
bubbles: true,
}),
);
});
expect(getByDisplayValue('jest infoHoc message')).toBeInTheDocument();
});Run Code Online (Sandbox Code Playgroud)
我的最后一行是错误的...我认为这是因为 mui 工具提示在正文末尾的 div 中显示消息,所以并不是真正在我的 rtl 树中...但是这棵树的第一个元素是 body !我知道我不应该测试 mui 组件,但这不是目的,我只是想确保 InfoHoc 具有正确的行为,使用 mui 工具提示或其他东西。
这是鼠标悬停操作后的 RTL 树:
<body>
<div>
<div
class="infoHoc"
>
<div>
jest div
</div>
<svg
aria-hidden="true"
class="MuiSvgIcon-root icon--right"
focusable="false"
viewBox="0 0 24 24"
>
<path
d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"
/>
</svg>
</div>
</div>
</body>Run Code Online (Sandbox Code Playgroud)
该事件很好,因为图标有一个标题属性,其中消息作为值,直到触发鼠标悬停为止。由于标题 attr 不在我的树上,我认为我的事件执行得很好;p
我测试错了?如果没有,你有办法解决我的问题吗?
谢谢你们 !
htt*_*ete 10
我认为这是最干净的方式。
it('Renders tooltip when hovering over button', async () => {
render(<Search />);
const button = await screen.findByRole('button');
await userEvent.hover(button);
const tip = await screen.findByRole('tooltip');
expect(tip).toBeInTheDocument();
});
Run Code Online (Sandbox Code Playgroud)
如果这仍然可以帮助您,您需要findBy代替在延迟后getBy显示Tooltip工具提示
it('should display info message on <div /> mouseover', async () => {
const Component = InfoHoc(<div>jest div</div>)({ message: 'jest infoHoc message' });
const { getByTitle, findByDisplayValue } = render(Component);
const icon = getByTitle('jest infoHoc message');
act(() => {
fireEvent(
icon,
new MouseEvent('mouseover', {
bubbles: true,
}),
);
});
// Wait for the tooltip to show up
const tooltipText = await findByDisplayValue('jest infoHoc message')
expect(tooltipText).toBeInTheDocument();
});
Run Code Online (Sandbox Code Playgroud)
旁注 1:我不确定你是否真的需要actaround fireEvent。测试库应该为你做这件事。
旁注 2:您可以使用具有更清晰语法(和函数)的user-event.hover
| 归档时间: |
|
| 查看次数: |
8785 次 |
| 最近记录: |