javascript - 如何用 Jest/ enzyme 来模拟 react refs?

标签 javascript reactjs jestjs enzyme

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

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 的函数,但我不知道该怎么做。

最佳答案

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

这里是我的问题的答案:

首先。需要对函数进行小的重构。

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 中设置 top 选项,但无论如何...

// ...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

关于javascript - 如何用 Jest/ enzyme 来模拟 react refs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52839909/

相关文章:

reactjs - React jest testing Google Maps Api,Uncaught TypeError : this. autocomplete.addListener 不是函数

javascript - 如何用 jest 测试 rxjs ajax 调用?

javascript - expect.anything() 不适用于 expect.toBe()

php - Javascript:跨域JSON请求问题

javascript - 如何在 jQuery 中保留文本区域中的换行符?

javascript - 具有多种颜色的 Raphael.js 复合路径

javascript - 如何使用 ReactJS 以两种方式使表中的列可排序

javascript - ReactJS:Express API 和 ReactJS 结构限制每行显示数据

javascript - Sequelize 多对多自关联

javascript - 数组映射和过滤 ReactJs