React Hook Testing Pass Reactive Variable To Hook

2023-01-07
React
testing
Typescript
Jest

The Problem

I'm still fairly new to React, and especially to the ways of testing it. So when I faced a hook that received a reactive variable and did different things depending on its state, I was puzzled how to test it as useState cannot be called outside of React context.

Additionally, due to some conditions I can't identify, tests were just hanging if I passed non-reactive variable - it might be a combination of software versions or something else, as I couldn't replicate it in simplified environment.

The Solution

Obvious in retrospect, the useState() could be called inside renderHook! So the solution looked like

    it('should return length', async () => {
        const {result: hookResult, waitForNextUpdate} = renderHook(() => {
            const [inputData, setInputData] = useState(["one"]);
            const hookResult = MyHook({inputValue: inputData});
            useEffect(() => {
                setInputData(["one", "two"]);
            }, []);
            return hookResult;
        });

        await waitForNextUpdate();

        expect(hookResult.current.result).toEqual(2);
    })

NOTE: waitForNextUpdate is needed only if the component is expected to re-render, it might not be required.