在 react-testing-library 中查询 font-awesome 元素

Query font-awesome element in react-testing-library

在我的渲染方法中我有

<span onClick={handleDelete} className="delete-action">
  <FontAwesomeIcon icon="trash-alt" />
</span>

使用 react-testing-library 如何访问上面的 span 元素。 这是我到目前为止尝试过的

getByText(<FontAwesomeIcon icon="trash-alt" />)

但错误提示 matcher.test 不是一个函数。我应该如何处理这个问题。

您收到此错误是因为 getByText 的第一个参数是 TextMatch,但您传递了一个组件。

显然,您可以将 title 属性传递给 FontAwesomeIcon,因为 this commit :

<span onClick={handleDelete} className="delete-action">
  <FontAwesomeIcon icon="trash-alt" title="some title"/>
</span>

然后您可以使用

简单地获取您的组件
getByTitle('some title');

注意:title prop 没有设置为由 font awesome 生成的 i 元素的属性,而是作为与 SVG 相关的 title 标签元素,但 react-testing-library

Will also find a title element within an SVG.

参考:https://testing-library.com/docs/dom-testing-library/api-queries#bytitle