How to test if iframe exists with React testing library?

Viewed 3392

In my React app I have a component which embeds an Instagram post.

It renders the following HTML structure:

<div data-testid="instagram"><iframe class="instagram-media instagram-media-rendered" id="instagram-embed-3" //etc....

I am using React testing library.

How do I write a test that checks if the iframe element exists and e.g with the CSS class instagram-media?

1 Answers

For accessibility purposes, it is recommended to always use the title attribute on an <iframe> to label/describe its content.

<div data-testid="instagram">
    <iframe title="Instagram embed" className="instagram-media ..." id="instagram-
embed-3"></iframe>
</div>

You can then test if the <iframe> element exists with the getByTitle query.

expect(screen.getByTitle('Instagram embed')).toBeInTheDocument();
Related