工具提示 MUI 和 React 测试库

Tooltip MUI and React testing library

我正在尝试在我的 React 应用程序上测试 Info HOC:

const InfoHOC = (HocComponent) => ({ message }) => (
  <>
    <Tooltip title={message}>
      <InfoIcon />
    </Tooltip>
    {HocComponent}
  </>
);

export default InfoHOC;

我已经简化了它。但是因为它使用 material ui 工具提示组件,我无法测试鼠标悬停时是否显示消息...

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

我的最后一行是错误的...我认为这是因为 mui 工具提示在 body 末尾的 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>

事件很好,因为图标有一个标题属性,消息作为值,直到触发鼠标悬停。由于 title attr 不在我的树上,我认为我的活动执行得很好;p

我测试错了?如果没有,您有解决我的问题的想法吗?

谢谢大家!

如果这仍然可以帮助您,您需要 findBy 而不是 getBy,因为 Tooltip 显示工具提示 after a delay

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

旁注 1:我不确定您是否真的需要 fireEvent 周围的 act。 testing-library 应该为您完成。

旁注 2:您可以使用 user-event,它具有更简洁的语法(和 .hover 函数)

我认为这是最干净的方式。

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