I am trying to test a custom hook using @testing-library/react-hooks but I have trouble testing the dependency. Let's use useEffect as an example:
import { renderHook } from '@testing-library/react-hooks';
import { useEffect } from 'react';
test('test dependency', () => {
const callback = jest.fn((value: number) => {});
let currentValue = 5;
renderHook(() => useEffect(() => callback(currentValue), [currentValue]));
expect(callback).toBeCalledTimes(1);
expect(callback).toHaveBeenLastCalledWith(5);
renderHook(() => useEffect(() => callback(currentValue), [currentValue]));
expect(callback).toBeCalledTimes(1); // error here: called 2 times in reality
expect(callback).toHaveBeenLastCalledWith(5);
currentValue = 6;
renderHook(() => useEffect(() => callback(currentValue), [currentValue]));
expect(callback).toBeCalledTimes(2);
expect(callback).toHaveBeenLastCalledWith(6);
});
Expected behaviour: useEffect is not called again with the same dependency list.
Actual behaviour: useEffect is called every time, probably because the context is destroyed and re-created betweeb renderHook.
I also tried putting the render method into a constant like this:
const myHook = () => useEffect(() => callback(currentValue), [currentValue]);
renderHook(myHook);
But no luck. Is there any way that I can test whether or not the dependency list works correctly?