如何在没有 UI 的情况下对 hook 进行 Jest 测试

How to make Jest test for hook without UI

我有下一个钩子

const useFetch => {
  let { state, dispatch } = useContext(AppContext);

  const fetch1 = async () => {
  ...code to fetch data (mocked)
  }
  const fetch2 = () => {
  ...
  }
  return {
    fetch1,
    fetch2,
    ...
  };
};

export default useFetch;

我需要创建笑话测试但是我不能直接做,因为它违反了钩子的规则,我不能渲染它,因为它没有 UI 渲染,它只是获取数据存储到上下文。

任何人都可以帮助我了解如何做吗?

提前致谢,对不起我的英语。

您可以创建一个仅用于测试目的的包装器组件并使用它。然而Testing Library has a great tool for that, hooks-testing-library。如果您有更多要测试的挂钩,它可能是您项目的一个很好的补充。