Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing `img.onLoad`/`img.onError` using Jest and React Testing Library

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();
});
like image 854
NotJustClarkKent Avatar asked Mar 02 '20 01:03

NotJustClarkKent


2 Answers

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)
like image 123
Hime Avatar answered Oct 13 '22 06:10

Hime


Explanation

  • <Avatar /> is rendered with default props, and in our case, contains an <img /> tag pointing to an optional profile image endpoint for the user.
  • We then use 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.
  • Finally we can now expect the <img /> was removed based on the logic within <Avatar />
like image 24
NotJustClarkKent Avatar answered Oct 13 '22 08:10

NotJustClarkKent