What is the suitable type for renderHook in react-testing-library and TypeScript?

6.8k Views Asked by At

I wanna test a custom hook with react-testing-library therefore, I add this code into beforeEach:

let renderedHook ;

beforeEach(() => {
  renderedHook = renderHook(() => useFetch());
});

test('.....', () => {
  expect(renderedHook.current.data).toBe(1);
});

the above code works well! but I'm using TypeScript, what's the suitable type for let renderedHook in this case?

2

There are 2 best solutions below

0
On BEST ANSWER

If your IDE or editor supports the "Go to Definition" feature, you can check the TS type of renderHook.

The return type of renderHook is RenderHookResult

E.g.

import { Renderer, renderHook, RenderHookResult } from '@testing-library/react-hooks';
import { useState } from 'react';

const useFetch = () => {
  const [data] = useState(1);
  return { data };
};

let renderedHook: RenderHookResult<unknown, { data: number }, Renderer<unknown>>;

describe('72601993', () => {
  beforeEach(() => {
    renderedHook = renderHook(() => useFetch());
  });

  test('.....', () => {
    expect(renderedHook.result.current.data).toBe(1);
  });
});

package version:

"@testing-library/react-hooks": "^8.0.0",
0
On

Though the Question is about suitable types, anyone who wants beforeEach functionality in tests and don't want to find suitable types from IDE support, you can create a function like setup

const setup = () => {
   const {result} = renderHook(() => useFetch());
}

Now you can use it every test without thinking about suitable test and it will show intellisense as well. The usage of the setup is shown below

it('should return data equal to 1' => {
  result = setup();
  expect(result.current.data).toBe(1)
})