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
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()
}
1 Comment
Community
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.
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();
});
});