Out team ran into a scenario this afternoon when writing a React Testing Library (RTL) test with Jest for our <Avatar />
ponent. 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 ponent. 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();
});
Out team ran into a scenario this afternoon when writing a React Testing Library (RTL) test with Jest for our <Avatar />
ponent. 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 ponent. 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();
});
Share
Improve this question
asked Mar 2, 2020 at 1:08
NotJustClarkKentNotJustClarkKent
1,0951 gold badge11 silver badges26 bronze badges
2 Answers
Reset to default 12get 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)
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 theonError
function that was bound atrender
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 />