测试自定义钩子的返回值

时间:2021-02-12 14:22:45

标签: react-hooks react-testing-library react-hooks-testing-library

我正在尝试为此自定义挂钩编写测试套件。

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 个答案:

答案 0 :(得分:2)

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,没有 return 语句,因此函数默认返回 undefined .但是调用 () => useInitialMount()() => { return useInitialMount(); } 的简短语法)将返回调用钩子的值。