【问题标题】:double fireEvent doesn't work in my react-testing-library testdouble fireEvent 在我的 react-testing-library 测试中不起作用
【发布时间】:2020-11-06 11:33:44
【问题描述】:

我正在使用 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。

【问题讨论】:

    标签: reactjs typescript react-testing-library


    【解决方案1】:

    您需要使用waitForwaitForElementToBeRemoved 来确保在对元素进行断言之前等待从DOM 中添加/删除元素。

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

    【讨论】:

      猜你喜欢
      • 2019-08-31
      • 1970-01-01
      • 2019-02-16
      • 2019-05-21
      • 2019-11-11
      • 2023-03-24
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多