I created an iframe component with ref and I wanted to create a unit test for that component, then I created a mock iframe so that the component could be run in the unit test, unfortunately the unit test failed, what's wrong with the following code, I'm a beginner at Jest. So how do you make the unit test successful?
component
import { forwardRef, useRef, useImperativeHandle } from 'react';
const Iframe = forwardRef(function Iframe(props, ref) {
const iframeRef = useRef(null);
useImperativeHandle(ref, () => {
return {
postMessage() {
iframeRef.current.contentWindow.postMessage(JSON.stringify({data: 'hello !'}), '*')
},
};
}, []);
return <iframe {...props} ref={iframeRef} />;
});
export default Iframe;
mock
// __mock__/iframe.js
import { useRef } from 'react';
import Iframe from './Iframe';
export default function App() {
const ref = useRef(null);
function handleClick() {
ref.current.postMessage({data: 'hello !'});
}
return (
<div>
<Iframe src={'https://www.google.com/'} ref={ref} />
<button onClick={handleClick}>
Send Message
</button>
</div>
);
}
jest
import * as React from 'react'
import { render, fireEvent, screen } from '@testing-library/react'
import Iframe from '../__mock__/iframe'
describe('iframe', () => {
it('call postMessage', () => {
render(<Iframe />)
const handleClick = jest.fn()
const button = screen.getByText(/Send Message/i)
fireEvent.click(button)
expect(handleClick).toHaveBeenCalled()
})
})
