Search code examples
reactjsunit-testingreact-testing-library

Query font-awesome element in react-testing-library


In my render method I have

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

Using react-testing-library how can I access the above span element. This is what I tried so far

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

but the error says matcher.test is not a function. How should I approach this.


Solution

  • You get this error because getByText's first argument is a TextMatch, but you passed a component.

    Apparently, you can pass a title prop to FontAwesomeIcon since this commit :

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

    and then you can simply get your component using

    getByTitle('some title');
    

    NB : title prop is not set as an attribute of the i element generated by font awesome, but rather as a title tag related to the SVG element, but react-testing-library

    Will also find a title element within an SVG.

    ref : https://testing-library.com/docs/queries/bytitle