11

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 Answer 1

28

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();
Sign up to request clarification or add additional context in comments.

4 Comments

note that toBeInTheDocument() requires testing-library/jest-dom
This just makes sure the title is there and is correct, it doesn't actually check that it's an iframe, or what its src attribute is, etc
@aarowman You can check what's in the src attribute with something like expect(screen.getByTitle('Instagram embed')).toHaveAttribute('src', '<src-url>'). Note that toHaveAttribute also requires testing-library/jest-dom.
@juliomalves Yes, I was pointing out that the accepted answer doesn't actually test the kind of element or attributes of it. It simply tests for the existence of a title, which could be on another element, or have other attributes (the answer is not fully complete). Your suggestion will help with src, and there is also more that could be added

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.