react-hooks-testing-library icon indicating copy to clipboard operation
react-hooks-testing-library copied to clipboard

renderHook (and rerender) doesn't properly infer overload type when using initialProps.

Open rnarcos opened this issue 3 years ago • 4 comments

  • @react-testing-library/react version (if applicable): 12.1.2
  • @react-testing-library/react-hooks version: 7.0.2
  • react version: 15.4.2
  • react-dom version (if applicable): 15.4.2
  • node version:
  • npm (or yarn) version:

Relevant code or config:

function useFoo(foo: string): string;
function useFoo(foo: number): number;
function useFoo(foo: string | number): string | number {
  return foo;
}


test('should allow hook overloading on re-renders', () => {
  renderHook(useFoo, { initialProps: 'string' })
});

What you did:

I have a react hook, that relies on overloading to solve different use-cases. Essentially, this hook has an overload that determines the appropriate way to resolve a value based on its parameter typeof.

What happened:

When faced with an overloadable hook, @react-testing-library/react-hooks isn't appropriately typing either the initialProps for the renderHook method, or the rerender method itself.

Reproduction:

Reproduction

Problem description:

Hook overloading only works when you explicitly call the hook and return it's value on the renderHook method, while when using the renderHook with the initialValue option, it doesn't properly generate the types to match the overload.

rnarcos avatar Apr 11 '22 14:04 rnarcos

Also, render result does not update its type definition based on the rerender output.

rnarcos avatar Apr 11 '22 14:04 rnarcos

We faced this issue even on the latest version (8.0.1), any idea?

alishi973 avatar Sep 19 '23 10:09 alishi973

Salutations !

I think you doesn't use renderHook well. You need to do this :

const { rerender } = renderHook((nextProps) => useMyHook(nextProps || initialProps)) 
rerender(myNextProps)

This solution work for me 👍


I think renderHook is not well designed to easily understand it and can be a good thing if in the future it can work like that :

const { render } = renderHook(useMyHook);
render(initialProps);
render(myNextProps);

emericspiroux avatar Oct 20 '23 14:10 emericspiroux

Sorry I'm a bit late to the party here. I believe this is a known limitation of generic type inference of overloaded functions in Typescript.

mpeyper avatar Dec 19 '23 22:12 mpeyper