How queryBy without html tags with React testing library

Viewed 19

I use React testing library for my unit test.

I want to test this of my React component:

return (
    <div>
      <p data-testid="my-string">
        {string}
      </p>
    </div>
  );

After I query queryByTestId the component I receive something like:

 <p class="css-1317scs-myString" data-testid="my-string">&lt;iframe src="src="https://my-site.com?id=6533cf73&autoplay=false" allowfullscreen seamless frameborder="0" allow="encrypted-media"&gt;&lt;/iframe&gt;</p>

So with all the html tags etc.

 expect(queryByTestId('my-string')).toBe(
      '<iframe src="https://my-site.com?id=6533cf73&autoplay=false" allowfullscreen seamless frameborder="0" allow="encrypted-media"></iframe>'
    );

I just want to test if <iframe src="https://my-site.com?id=6533cf73&autoplay=false" allowfullscreen seamless frameborder="0" allow="encrypted-media"></iframe> is exactly defined like this.

How do I get rid of all those html tags. Or do I have to use another approach?

1 Answers

To get the content of all the elements inside of the queried element, you should use textContent on the queried element.

expect(queryByTestId('my-string').textContent)
    .toBe('&lt;iframe src="src="https://my-site.com?id=6533cf73&autoplay=false" allowfullscreen seamless frameborder="0" allow="encrypted-media"&gt;&lt;/iframe&gt;');

Yes, the rendered string in your component will swap out the < angle bracket character for &lt;. React encodes the < and > characters automatically to prevent XSS attacks.

If you really want the brackets rendered, you can use React's dangerouslySetInnerHtml attribute. You can use it like so:

<p data-testid="my-string" 
   dangerouslySetInnerHTML={string}
></p>

After applying the dangerouslySetInnerHTML attribute, you should see the actual < brackets rendered in your app and in your test.

Related