测试自定义钩子的返回值 [英] Testing return value of a custom hook

查看:62
本文介绍了测试自定义钩子的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write a test suit for this custom hook.

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";这是我的尝试:

Very simple returns true or false.
As I saw, I should use "@testing-library/react-hooks" and here is my try:

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 这没有意义它应该是对还是错.

but I got undefined which doesn't make sense it should be either true or false.

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

PS: the code works as expected on the project.

推荐答案

renderHook 调用的语法在您的测试中不太正确.您应该从 renderHook 回调中返回 useInitialMount(),而不仅仅是在其中调用它(因此您会得到 undefined).

The syntax for the renderHook call is not quite right in your test. You should return useInitialMount() from renderHook callback, not just call it inside it (hence why you get 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(); } 的简短语法)将返回调用钩子的值.

To clarify, the difference here is that calling () => { useInitialMount(); }); returns undefined, there are no return statements so the function will return undefined by default. But calling () => useInitialMount() (which is short syntax for () => { return useInitialMount(); }) will return the value of calling the hook.

这篇关于测试自定义钩子的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆