Cagri Uysal
Cagri Uysal

Reputation: 394

React Testing library - simulate iFrame onLoad

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.

Upvotes: 2

Views: 2152

Answers (2)

Massimo Mxswat
Massimo Mxswat

Reputation: 73

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();
  });
});

Upvotes: 2

joedium
joedium

Reputation: 41

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()

}

Upvotes: 4

Related Questions