Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 976
chandan_kr_jha Avatar asked Jun 26 '20 03:06

chandan_kr_jha


People also ask

How do I get the element by className in React testing library?

To find elements by className in React testing library: Render a component and destructure the container object from the result. Use the getElementsByClassName() method on the container to find elements by class name.

Can I use font awesome CDN in React?

We'll cover the basics of using the official react-fontawesome component (described below), which uses the SVG + JS method to render icons. But you can opt to use the Web Fonts + CSS method if you prefer. Follow the steps below to set up the react-fontawesome component in your project.


1 Answers

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/dom-testing-library/api-queries#bytitle

like image 56
aquinq Avatar answered Sep 21 '22 23:09

aquinq