首页 > 解决方案 > 如何用玩笑/酶模拟反应参考?

问题描述

我开始学习应用程序测试,我需要测试功能。我有一些组件:

export class Countries extends React.Component<Props, State> {
  private countriesList: React.RefObject<HTMLDivElement> = React.createRef<
    HTMLDivElement
  >();

  public componentDidMount(): void {
    setTimeout(this.whenCDM, 1);
  }


  public render(): React.ReactNode {
    return (
      <div ref={this.countriesList}>
      </div>
    );
  }

  private whenCDM = (): any => {
    if (this.countriesList.current) {
      this.whenComponentDidMount(
        this.countriesList.current.getBoundingClientRect().top
      );
    }
  };
}

我想测试名为 whenCDM 的函数,但我不知道该怎么做。

标签: javascriptreactjsjestjsenzyme

解决方案


我终于找到了答案。我只是不明白什么是“模拟”。

这是我的问题的答案:

第一的。需要小的重构功能。

private whenCDM = (countriesList:any): any => {
    if (countriesList.current !== null) {
      this.whenComponentDidMount(
        countriesList.current.getBoundingClientRect().top
      );
    }
};

然后在 cDM 中:

public componentDidMount(): void {
    setTimeout(this.whenCDM(this.countriesList), 1);
}

然后在测试文件中创建模拟函数: 我想,我可以在 getBoundingClientRect 中设置只有顶级选项,但无论如何......

// ...code
it("whenCDM", () => {
    const getCountriesListRef = () => {
      return {
        current: {
          getBoundingClientRect: () => {
            return {
              bottom: 624,
              height: 54,
              left: 15,
              right: 360,
              top: 570,
              width: 345,
              x: 15,
              y: 570
            };
          }
        }
      };
    };

    const instance = wrapper.instance();
    expect(instance.whenCDM(getCountriesListRef()));
  });
// ...code

推荐阅读