最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Testing `img.onLoad``img.onError` using Jest and React Testing Library - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 12

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)

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 />
发布评论

评论列表(0)

  1. 暂无评论