使用Jest和Reaction测试库测试`img.onLoad`/`img.onError` [英] Testing `img.onLoad`/`img.onError` using Jest and React Testing Library

查看:0
本文介绍了使用Jest和Reaction测试库测试`img.onLoad`/`img.onError`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天下午,Out团队在使用Jest为<Avatar />组件编写Reaction测试库(RTL)测试时遇到了一个场景。具体地说,我们希望测试<img />标记在无法加载(onError被触发)以匹配组件的预期最终视图时是否从DOM中删除。由于某些原因,在<img />DOM元素上使用fireEvent对我们来说并不是一目了然的,我们没有在网上找到这个显式的解决方案,所以我们想要共享。正如您可以想象的那样,这也适用于onLoad等其他事件。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();
});

推荐答案

使用TestID或Role获取镜像,然后使用FireEvent分别调用onLoadOnError函数

const image = getByRole('img')

fireEvent.load(image);

用于onError

fireEvent.error(image)

这篇关于使用Jest和Reaction测试库测试`img.onLoad`/`img.onError`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆