Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 349
Martin Rützy Avatar asked Oct 15 '25 20:10

Martin Rützy


1 Answers

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",
like image 187
slideshowp2 Avatar answered Oct 17 '25 12:10

slideshowp2