I am attempting to fire a load event where the target property in the load event is customised.
test:
const onLoad: ImageSrcSetProps['onLoad'] = (e, options) => void vi.fn(e, options);
// pass the mock to the component to ensure it's called correctly when the image loads
renderWithProviders(<ImageSrcSet {...getProps({ onLoad })} />);
// crux of issue:
const image = screen.getByRole('img');
fireEvent.load(image, { target: { currentSrc: 'foo' } }); // you can't do this.
component
const handleOnLoad = useCallback(
(e: React.MouseEvent<HTMLImageElement>) => {
console.log('currentSrc!!!--->', e.target.currentSrc, '<----');
},
[onLoad]
);
...
<img
srcSet={getImageSrcSet}
src={placeholderGif}
role="img"
onLoad={handleOnLoad}
/>
( The currentSrc is the image that the browser loaded – it varies based on screen size )
I have tried:
Object.defineProperty(global.Image.prototype, 'currentSrc', {
writable: true,
});
But this will break vitest ( and probably jest too )
Error: Uncaught [Error: cannot spy on a non-function value] which is caused by mock `onLoad`
So yeah, catch-22 and stuck. Suggestions?