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();
});