Examples
Testing a modal presented from a trigger
This example shows how to test a modal that is presented from a trigger. The modal is presented when the user clicks a button.
Example component
src/Example.tsx
import{IonButton,IonModal}from'@ionic/react';
exportdefaultfunctionExample(){
return(
<>
<IonButtonid="open-modal">Open</IonButton>
<IonModaltrigger="open-modal">Modal content</IonModal>
</>
);
}
Testing the modal
src/Example.test.tsx
import{IonApp}from'@ionic/react';
import{ fireEvent, render, screen, waitFor }from'@testing-library/react';
importExamplefrom'./Example';
test('button presents a modal when clicked',async()=>{
render(
<IonApp>
<Example/>
</IonApp>
);
// Simulate a click on the button
fireEvent.click(screen.getByText('Open'));
// Wait for the modal to be presented
awaitwaitFor(()=>{
// Assert that the modal is present
expect(screen.getByText('Modal content')).toBeInTheDocument();
});
});
Testing a modal presented from useIonModal
This example shows how to test a modal that is presented using the useIonModal
hook. The modal is presented when the user clicks a button.
Example component
src/Example.tsx
import{IonContent, useIonModal,IonHeader,IonToolbar,IonTitle,IonButton,IonPage}from'@ionic/react';
constModalContent:React.FC=()=>{
return(
<IonContent>
<div>Modal Content</div>
</IonContent>
);
};
constExample:React.FC=()=>{
const[present]=useIonModal(ModalContent);
return(
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle>Blank</IonTitle>
</IonToolbar>
</IonHeader>
<IonContentfullscreen={true}>
<IonButtonexpand="block"className="ion-margin"onClick={()=>present()}>
Open
</IonButton>
</IonContent>
</IonPage>
);
};
exportdefaultExample;
Testing the modal
src/Example.test.tsx
import{IonApp}from'@ionic/react';
import{ fireEvent, render, screen, waitFor }from'@testing-library/react';
importExamplefrom'./Example';
test('should present ModalContent when button is clicked',async()=>{
render(
<IonApp>
<Example/>
</IonApp>
);
// Simulate a click on the button
fireEvent.click(screen.getByText('Open'));
// Wait for the modal to be presented
awaitwaitFor(()=>{
// Assert that the modal is present
expect(screen.getByText('Modal Content')).toBeInTheDocument();
});
});