2

I have a component that renders iFrame inside of it. I want to test iFrame's onLoad functionality but it doesn't triggers simply with the testing library's render function. Can I programmatically simulate iFrame's onLoad event with testing library.

2 Answers 2

4

I was stuck on this one and used:

it('should call the onLoad event'), async () => {
  const {container} = render(<MyComponent />)
  fireEvent.load(container.querySelector('iframe')
await waitFor(() => expect(yourOnLoadEvent).toHaveBeenCalled()

}
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
2

Yes, you can. I stumbled upon this question and decided to share my working code. I tried to use container.querySelector('iframe'), but it seems like it can't find the iframe, so I took the approach of using testid

import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { useState } from 'react';

const MyComponent = () => {
  const [isLoaded, setIsLoaded] = useState(false);

  return (
    <div>
      <iframe
        data-testid="google-iframe"
        src="google.com"
        title="google"
        onLoad={() => setIsLoaded(true)}
      />
      {isLoaded && <span>OnLoad Triggered!</span>}
    </div>
  );
};

function renderComponent() {
  render(<MyComponent />);
}

test('Should show the OnLoad message once the iframe has loaded', async () => {
  renderComponent();

  fireEvent.load(screen.getByTestId('google-iframe')!);

  await waitFor(() => {
    expect(screen.getByText('OnLoad Triggered!')).toBeInTheDocument();
  });
});

Comments

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.