I am trying to figure out how to test callbacks that are given as props to react functional components using jest and react testing library.
Example scenario: I am testing a component that renders a modal. When a user clicks the 'Close' button on the modal, the parent component hides the modal. So logic is this:
const ParentComp = () => {
const [openModal, setOpenModal] = useState(false);
return (
<>
<MyModal showModal={openModal} onClose={() => setOpenModal(false)} />
<button data-testid="open-modal-button" onClick={()=> setOpenModal(true)}>Test</button>
</>
}
const MyModal = ({showModal, onClose}) => {
return (
{showModal && <>
<div>This is a modal</div>
<button data-testid="close-modal-button" onClick={onClose}>Close</button>
</>
}
}
I am mocking the modal in my tests for the parent component as I dont want to rely on the actual modal component. With react testing library, how do I trigger the onClose in my parent component so I can test the setOpenModal(false)?
jest.mock('../MyModal');
beforeEach(() => {
MyModal.mockImplementation(() => <div data-testid="my-modal" />);
});
it('should close the modal' () => {
const { container, getByTestId } = render(
<MyParentComp />
);
const openModalButton = getByTestId('open-modal-button');
fireEvent.click(openModalButton);
const myModal = getByTestId('my-modal');
expect(myModal).toBeDefined();
//How to test setOpenModal(false) on parent component?
});
onClick
that fires the close event, and then you canfireEvent
on it. – tmdesigned