【问题标题】:How to find an svg in a jest test?如何在玩笑测试中找到 svg?
【发布时间】:2021-02-01 08:45:11
【问题描述】:

[第二次更新] 我正在寻找它无法识别的属性的 svg,并且感谢用户评论,我已经纠正了我的错误,但是我如何寻找我的 svg 来进行开玩笑测试?

我在我的 react 应用程序中实现了一个笑话测试,它应该检测一个具有打开弹出窗口功能的图标。

it('popup is opened when icon is clicked', async () => {
  Api.get.mockResolvedValueOnce(form);
  popupActions.showPopup = jest.fn(() => () => {});
  const { findByRole } = renderWithRedux(
    <CardInput translate={(text) => text} />,
    initialState
  );
  const iconWrapper = await findByRole('info');


  fireEvent.click(??);
  await wait(() =>
    expect(popupActions.showPopup).toHaveBeenCalledWith(
      expect.objectContaining({
        message: {
          text: 'message_front',
        },
      })
    )
  );
});

在这里我要检索包装 svg 的 div,但我不知道如何检索 svg,这将是“iconwrapper”的子组件。

<div role="info">
   <svg class="root" style="position: absolute; cursor: pointer;">
     <g stroke="none" stroke-width="1" fill="none">
        <polygon points="0 0 24 0 24 24 0 24">
        </polygon>
          <path d="M11,7 L13,7 L13,9 L11,9 L11,7 Z" fill="#404040" fill-rule="nonzero">
          </path>
     </g>
    </svg>
   
      

如果我做错了什么,有这些信息的人可以告诉我吗?我无法看到我的错误。 最好的问候,并提前感谢大家的时间和帮助。

【问题讨论】:

  • svg 元素没有 alt 属性,参见例如stackoverflow.com/q/22823770/3001761
  • @jonrsharpe 非常感谢!我明白了,但在文档中,我只看到通过标题获取带有开玩笑的 svg 的可能性。这是唯一的方法吗?

标签: reactjs react-native unit-testing testing jestjs


【解决方案1】:

最后,我通过将 svg 包装在我声明角色属性的 div 中解决了这个问题。然后我使用 findByRole 方法和 firstchild 方法来获取 svg

const iconWrapper = await findByRole('info');
fireEvent.click(iconWrapper.firstChild);

【讨论】:

    猜你喜欢
    • 2021-01-01
    • 2017-11-28
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 2021-03-19
    • 2020-06-30
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多