Issue
This Content is from Stack Overflow. Question asked by meez
I use React testing library for my unit test.
After I query queryByTestId
the component I receive something like:
<p class="css-1317scs-myString" data-testid="my-string"><iframe src="src="https://my-site.com?id=6533cf73&autoplay=false" allowfullscreen seamless frameborder="0" allow="encrypted-media"></iframe></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?
Solution
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('<iframe src="src="https://my-site.com?id=6533cf73&autoplay=false" allowfullscreen seamless frameborder="0" allow="encrypted-media"></iframe>');
Yes, the rendered string in your component will swap out the <
angle bracket character for <
. 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.
This Question was asked in StackOverflow by meez and Answered by g0rb It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.