使用Jest和Reaction测试库测试`img.onLoad`/`img.onError`

原学程将引见应用Jest以及Reaction尝试库尝试`img.onLoad`/`img.onError`的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。

使用Jest和Reaction测试库测试`img.onLoad`/`img.onError` 教程 第1张

成绩描写

明天下昼,Out团队在应用Jest为<Avatar />组件编辑Reaction尝试库(RTL)尝试时碰到了1个场景。详细天说,我们愿望尝试<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分离挪用onLoad或者OnError函数

const image = getByRole('img')

fireEvent.load(image);

用于onError

fireEvent.error(image)

佳了闭于应用Jest以及Reaction尝试库尝试`img.onLoad`/`img.onError`的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。