3

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

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;
};

非常简单的返回truefalse
正如我所看到的,我应该使用@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这没有意义,它应该是trueor false

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

4

1 回答 1

3

调用的语法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);
});

编辑:为了澄清,这里的区别在于:

调用return ,没有 return 语句,因此该函数将默认() => { useInitialMount(); });返回。undefinedundefined

但是调用() => useInitialMount()(这是 的简短语法() => { return useInitialMount(); })将返回调用钩子的值。

参考:箭头函数 > 函数体

于 2021-02-12T17:20:52.887 回答