【问题标题】:Testing `img.onLoad`/`img.onError` using Jest and React Testing Library使用 Jest 和 React 测试库测试 `img.onLoad`/`img.onError`
【发布时间】:2020-06-14 07:19:56
【问题描述】:

今天下午,Out 团队在使用 Jest 为我们的 <Avatar /> 组件编写 React 测试库 (RTL) 测试时遇到了一个场景。具体来说,我们想测试当加载失败(onError 被触发)时,<img /> 标记已从 DOM 中删除,以匹配预期的组件最终视图。出于某种原因,在<img /> DOM 元素上使用fireEvent 对我们来说并不是很明显,我们没有在网上找到这个明确的解决方案,所以我们想要分享。可以想象,这也适用于其他事件,例如 onLoadMore 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();
});

【问题讨论】:

    标签: javascript jestjs react-testing-library


    【解决方案1】:

    使用 testId 或 role 获取图像,然后使用 fireEvent 分别调用 onLoadOnError 函数

    const image = getByRole('img')
    
    fireEvent.load(image);
    

    对于错误

    fireEvent.error(image)
    

    【讨论】:

      【解决方案2】:

      说明

      • &lt;Avatar /&gt; 使用默认道具呈现,在我们的例子中,包含一个 &lt;img /&gt; 标记,指向用户的可选配置文件图像端点。
      • 然后我们在该 DOM 元素上使用 fireEvent,触发在 render 时间绑定的 onError 函数,模拟未设置用户头像的失败/404 情况。
      • 最后,我们现在可以预期 &lt;img /&gt; 已根据 &lt;Avatar /&gt; 中的逻辑被删除

      【讨论】:

        猜你喜欢
        • 2017-11-11
        • 2020-03-24
        • 2020-06-01
        • 2021-09-20
        • 2019-04-22
        • 2021-06-04
        • 2021-06-14
        • 2021-05-26
        • 2021-12-06
        相关资源
        最近更新 更多