How to test for a state change after image element load event?

Viewed 149

I have the following code:

return (
    <img
        ref={imgRef}
        src={url}
        alt={alt}
        onLoad={() => {
          if (imgRef.current?.naturalWidth) setIsImgLoaded(true);
        }}
        style={!isImgLoaded ? { display: 'none' } : {}}
    />

So when the image finishes loading (by checking its naturalWidth), I update the isImgLoaded to true and display it (at the beginning, as you can see, I have display: none set for the image).

In my tests, whenever I try to do:

expect(screen.getByRole('img')).toExist()

I get an error TestingLibraryElementError: Unable to find role="img" , even if I try to use waitFor or findByRole.

What can I do?

1 Answers

You need to explicitly trigger the image's onLoad event to trigger its callback and make the image visible during the test.

test("image is visible after loading", () => {
    render(<TestComponent />)
    // Use `{ hidden: true }` to access the image while it's not visible
    const image = screen.getByRole('img', { hidden: true })
    fireEvent.load(image)
    // No longer requires `{ hidden: true }` as the image is now visible
    expect(screen.getByRole('img')).toBeInTheDocument()
});
Related