【问题标题】:How to test window functions within a react component?如何在反应组件中测试窗口功能?
【发布时间】:2021-09-29 14:54:56
【问题描述】:

Jest 中有没有对这个 react 功能组件进行测试?

问题是,当我在 modalIsVisible 处于活动状态的情况下启动此组件时,窗口打印会打开一个 iframe。

type SixLabelReportType = {
  labels: LabelProps[];
  modalIsVisible: boolean;
  setModalIsVisible: Dispatch<SetStateAction<boolean>>;
};
const SixLabelReport: React.FC<SixLabelReportType> = (
  params: SixLabelReportType
) => {
  const { labels, modalIsVisible, setModalIsVisible } = params;

  useEffect(() => {
    if (modalIsVisible) {
      window.print();
      setModalIsVisible(false);
    }
  }, [modalIsVisible]);

  return (
    <S.Modal show={modalIsVisible} data-testid='six-label-report-modal'>
      <S.Container data-testid='six-label-report-container'>
        {labels.map((label, idx) => {
          const { deliveryData, recipientData, senderData } = label;
          return (
            <Label
              key={idx}
              deliveryData={deliveryData}
              recipientData={recipientData}
              senderData={senderData}
              data-testid='six-label-report-label'
            />
          );
        })}
      </S.Container>
    </S.Modal>
  );
};

【问题讨论】:

    标签: javascript reactjs printing jestjs window


    【解决方案1】:

    只要监视window.open

    const spy = jest.spyOn(window, 'open');
    expect(spy).toHaveBeenCalled();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-28
      • 1970-01-01
      相关资源
      最近更新 更多