【问题标题】:Testing return value of a custom hook测试自定义钩子的返回值
【发布时间】:2021-02-12 14:22:45
【问题描述】:

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

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

非常简单的返回true 或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,这没有意义,它应该是true 或false。

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

【问题讨论】:

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


    【解决方案1】:

    renderHook 调用的语法在您的测试中不太正确。

    注意大括号,你应该从renderHook回调中返回useInitialMount(),而不是在里面调用它(这就是你得到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(); } 的简短语法)将返回调用钩子的值。

    参考:Arrow Functions > Functions body。

    【讨论】:

    • 语法正是文档中所说的github.com/testing-library/react-hooks-testing-library。结果有值,但当前值是不确定的。
    • @morteza 我添加了一个编辑来澄清我的答案。现在让我知道这是否有意义。
    • 非常感谢它的工作我错过了重点
    猜你喜欢
    • 2020-03-25
    • 2022-01-13
    • 2020-07-10
    • 2020-06-01
    • 2020-02-19
    • 2020-05-25
    • 1970-01-01
    • 2020-01-26
    • 2021-04-25
    相关资源
    最近更新 更多