1

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?

Lin Du
  • 88,126
  • 95
  • 281
  • 483
Martin Rützy
  • 415
  • 1
  • 11
  • 22

2 Answers2

3

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",
Lin Du
  • 88,126
  • 95
  • 281
  • 483
0

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)
})
Md Rafee
  • 5,070
  • 3
  • 23
  • 32