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

cha*_*jha 5 unit-testing reactjs react-testing-library

在我的渲染方法中,我有

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

Run Code Online (Sandbox Code Playgroud)

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

getByText(<FontAwesomeIcon icon="trash-alt" />)
Run Code Online (Sandbox Code Playgroud)

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

aqu*_*inq 6

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

显然,你可以传递一个title道具,FontAwesomeIcon因为这个提交

<span onClick={handleDelete} className="delete-action">
  <FontAwesomeIcon icon="trash-alt" title="some title"/>
</span>
Run Code Online (Sandbox Code Playgroud)

然后你可以简单地使用你的组件

<span onClick={handleDelete} className="delete-action">
  <FontAwesomeIcon icon="trash-alt" title="some title"/>
</span>
Run Code Online (Sandbox Code Playgroud)

注意:titleprop 不是设置为ifont awesome 生成的元素的属性,而是设置为与元素title相关的标签SVG,但是react-testing-library

还将在 SVG 中查找标题元素。

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