如何测试 useEffect 中的函数被调用?

时间:2021-03-22 18:33:52

标签: reactjs unit-testing react-hooks karma-runner enzyme

我的组件中有一个 useEffect 函数,它调用传递给组件的 rtwo 函数,如下所示:

组件:

const FetcherComponent = ({ controller = {}, ...props }) => {
  const { submitData, checkData } = controller;
  const { poll } = props;

  useEffect(() => {
    const init = async () => {
      if (poll) {
        const resp = await submitData();

        if (resp.failed) {
          return;
        }
      }
      await checkData(poll);
    };

    init();
  }, [poll, submitData, checkData]);

  return (
    <Spinner />
  );
};

函数来自我创建的一个钩子。

钩子:

function useFetcher(props = {}) {
  const handleSubmitData = useCallback(
    useErrorHandler(() => () => {}, callback),
    []
  );

  const handleStatusCheck = useCallback(
    useErrorHandler((isPolling = false) => () => {}, callback),
    []
  );

  const handleSuccessResponse = useCallback(
    ({ data, showStatusPage = false }) => {},
    [deps]
  );

  const handleErrorResponse = useCallback((error) => {}, [deps]);

  const submitData = useCallback(async () => {
    const submission = await handleSubmitData();
    // ...
    // ...
  }, [deps]);

  const checkData = useCallback(
    async (isPolling) => {
      const statusCheck = await handleStatusCheck(isPolling);
      // ...
      // ...
    },
    [deps]
  );

  return {
    submitData,
    checkData,
  };
}

这是当前如何使用它的示例。

集成:

const ExampleComponent = ({ props }) => {
  const statusChecker = useFetcher();

  return <StatusChecker controller={statusChecker} isPolling />;
};

如何断言 submitDatacheckData 这两个函数在 poll 属性值为 true 时被调用?

我尝试了多种方法,但似乎没有任何效果。我的应用程序将 Karma 与 Enzyme 结合使用。

0 个答案:

没有答案