双 fireEvent 在我的 react-testing-library 测试中不起作用

double fireEvent doesn't work in my react-testing-library test

我正在使用 React 测试库和 Typescript。

我需要测试我的菜单:单击一个按钮,测试带有内容的 Popper 是否可见,再次单击按钮并测试带有内容的 Popper 是否不可见。我还测试触发按钮是否一直可见。

import React from 'react';
import { fireEvent, render, RenderResult, screen } from '@testing-library/react';
import { AMenu } from './AMenu';

const firstMenuItemLabel = 'Location 1';
const menuTriggerLabel = 'locations';

describe('<AMenu />', () => {
  let component: RenderResult;
  let button: Element;

  beforeEach(() => {
    component = render(
      <AMenu
        classes={{
          root: '',
          menuButton: '',
        }}
      />
    );
    button = component.getByText(menuTriggerLabel).parentElement as Element;
  });

  it('should show and hide on click on menu trigger',  () => {
    expect(button).toBeVisible();
    expect(component.queryAllByText(firstMenuItemLabel)).toHaveLength(0);
    fireEvent.click(button);
    expect(button).toBeVisible();
    expect(component.getByText(firstMenuItemLabel)).toBeVisible();
    fireEvent.click(button);
    expect(component.queryAllByText(firstMenuItemLabel)).toHaveLength(0); // <- here it fails
  });
});

在浏览器中一切正常。 AMenu 不依赖于屏幕尺寸。

当我 console.log(component.debug()) 时,我可以看到呈现的组件 Popper 在第一次事件触发后可见。第二次点火不会改变组件 HTML.

您需要使用 waitForwaitForElementToBeRemoved 来确保您正在等待元素从 DOM 变为 added/removed 之前断言他们。

参见:https://testing-library.com/docs/guide-disappearance/#waiting-for-appearance