测试自定义钩子的返回值

IT技术 reactjs react-hooks react-testing-library react-hooks-testing-library
2021-05-26 00:54:23

我正在尝试为这个自定义钩子编写一个测试套装。

export const useInitialMount = () => {
  const isFirstRender = useRef(true);

  // in the very first render the ref is true, but we immediately change it to false.
  // so the every renders after will be false.
  if (isFirstRender.current) {
    isFirstRender.current = false;
    return true;
  }
  return false;
};

非常简单的返回真或假。
正如我所见,我应该使用@testing-library/react-hooks ,这是我的尝试:

test("should return true in the very first render and false in the next renders", () => {
    const {result} = renderHook(() => {
      useInitialMount();
    });
    expect(result.current).toBe(true);
  });

但我得到了 undefined 这没有意义它应该是真还是假。

PS:代码在项目上按预期工作。

1个回答

renderHook调用的语法在您的测试中不太正确。你应该useInitialMount()renderHook回调中返回,而不仅仅是在它里面调用它(这就是为什么你得到undefined)。

test('should return true in the very first render and false in the next renders', () => {
    const { result } = renderHook(() => useInitialMount());
    expect(result.current).toBe(true);
});

编辑:澄清一下,这里的区别在于调用() => { useInitialMount(); });返回undefined,没有返回语句,因此函数将undefined默认返回但是调用() => useInitialMount()(这是 的简短语法() => { return useInitialMount(); })将返回调用钩子的值。