I want to write Unit Test for the customhook useImageLoad. I want to check how many times "onImageLoad" parameter is called.
Initially I was using onImageLoad inside useEffect but it was rendering every seconds continously. So I have to use it with useCallback hook to run only once. Now its working fine as expected but I want to write a unit test which could get me how many times onImageLoad function has been called.
Below is the function:-
useImageLoad.ts
import { useEffect, useCallback, useState } from 'react';
export const useImageLoad = (src: string, onImageLoad: () => void = () => {}) => {
const [isImageLoaded, setImageIsLoaded] = useState(false);
useCallback(() => {
onImageLoad();
}, [onImageLoad]); // render 2 times
useEffect(() => {
const newImage = new Image();
newImage.src = src;
newImage.onload = () => {
setImageIsLoaded(true);
};
return () => {
newImage.onload = null;
};
}, [src]);
return isImageLoaded;
};
I am trying some way by looking into some tutorial but couldn't help myself how to excetute and run test.
useImageLoad.spec.ts
import React from 'react';
import { render } from '@testing-library/react';
import { useImageLoad } from './useImageLoad';
type HookWrapperProps = {
src: string;
onImageLoad: () => void;
};
// This is just a simple wrapper component since it's awkward to test hooks that rely on
// React lifecycle methods.
const HookWrapper = ({ src, onImageLoad }: HookWrapperProps) => {
const isImageLoaded = useImageLoad(src, onImageLoad);
console.log(isImageLoaded, 'isImageLoaded');
return <div>{isImageLoaded}</div>;
};
describe('UseImageLoad tests', () => {
it('should return a repository locator', async () => {
const result = render(<HookWrapper src="test" onImageLoad={() => {}} />);
});
});
Is it possible to achieve same with renderHook ?
I am totally noob in unit test. Excuse my code. Any help will be greatly appreciated. Thanks in advance.