testing-library / react-testing-library

🐐 Simple and complete React DOM testing utilities that encourage good testing practices.
https://testing-library.com/react
MIT License
19.04k stars 1.11k forks source link

`hydrate` option does not work in `renderHook` #1340

Closed immois closed 4 months ago

immois commented 4 months ago

I always use Jest to unit test my projects. I had used the hydrate option before in my components but this is the first time I've used it in a hook and it didn't work as expected.

Relevant code or config:

I have as an example the simple hook useCounter

import { useCallback, useState } from 'react';

export const useCounter = (): { count: number; increment: () => void } => {
  const [count, setCount] = useState(0);

  const increment = useCallback(() => setCount(x => x + 1), []);

  return { count, increment };
};
it('should increment counter', () => {
    const { result } = renderHook(() => useCounter(), { hydrate: true });

    act(() => {
      result.current.increment()
    })

    expect(result.current.count).toBe(0)
  });

What you did:

Testing server-side hook with hydrate option exposing renderHook method

What happened:

The hook was executed immediately on the server side

image

Problem description:

The renderHook method exposes a hydrate option that according to the documentation if set to true should render server-side and as a result the hook should be static and non-interactive.

eps1lon commented 4 months ago

Hydration means it makes static content interactive. Just like using hydrate in render makes a button interactive, hydrate in renderHook makes hooks interactive.

immois commented 4 months ago

Thanks for the answer, I see that I misunderstood how the hydrate option works. What I was trying to do is test how the hook will behave when rendered on the server. Do you have any ideas how I could do this?

eps1lon commented 4 months ago

Render it in a Node.js environment with a react-dom/server API of your choice. Hard to give good advise without knowing what you want to test. But I suspect most of the interesting behavior of hooks happens on the client not server.

Closing in favor of https://github.com/testing-library/react-testing-library/issues/1120