Out team ran into a scenario this afternoon when writing a React Testing Library (RTL) test with Jest for our <Avatar />
component. Specifically, we wanted to test that the <img />
tag was removed from the DOM when it fails to load (onError
is triggered) to match the expected final view of component. For some reason, using fireEvent
on the <img />
DOM Element was not immediately obvious to us and we didn't find this explicit solution online so we wanted share. As you can imagine, this will work for other events such as onLoad
as well. More about RTL Events.
it('should render with only initials when avatar image is NOT found', async() => {
const { container } = render(<Avatar {...defaultMocks} />);
const avatarImg = container.querySelector('img');
expect(avatarImg).toBeInTheDocument();
fireEvent(avatarImg, new Event('error'));
expect(avatarImg).not.toBeInTheDocument();
});
get the image using testId or role then use fireEvent to call onLoad
or OnError
functions respectively
const image = getByRole('img')
fireEvent.load(image);
for onError
fireEvent.error(image)
<Avatar />
is rendered with default props, and in our case, contains an <img />
tag pointing to an optional profile image endpoint for the user.fireEvent
on that DOM element, triggering the onError
function that was bound at render
time mocking a failed/404
case where a user avatar was not set.<img />
was removed based on the logic within <Avatar />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With