示例
测试从触发器呈现的模态
此示例展示了如何测试从触发器呈现的模态。当用户点击按钮时会呈现模态。
示例组件
src/Example.tsx
import { IonButton, IonModal } from '@ionic/react';
export default function Example() {
return (
<>
<IonButton id="open-modal">Open</IonButton>
<IonModal trigger="open-modal">Modal content</IonModal>
</>
);
}
测试模态
src/Example.test.tsx
import { IonApp } from '@ionic/react';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import Example from './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
await waitFor(() => {
// Assert that the modal is present
expect(screen.getByText('Modal content')).toBeInTheDocument();
});
});
测试从 useIonModal 呈现的模态
此示例展示了如何测试使用 useIonModal
钩子呈现的模态。当用户点击按钮时会呈现模态。
示例组件
src/Example.tsx
import { IonContent, useIonModal, IonHeader, IonToolbar, IonTitle, IonButton, IonPage } from '@ionic/react';
const ModalContent: React.FC = () => {
return (
<IonContent>
<div>Modal Content</div>
</IonContent>
);
};
const Example: React.FC = () => {
const [present] = useIonModal(ModalContent);
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle>Blank</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent fullscreen={true}>
<IonButton expand="block" className="ion-margin" onClick={() => present()}>
Open
</IonButton>
</IonContent>
</IonPage>
);
};
export default Example;
测试模态
src/Example.test.tsx
import { IonApp } from '@ionic/react';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import Example from './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
await waitFor(() => {
// Assert that the modal is present
expect(screen.getByText('Modal Content')).toBeInTheDocument();
});
});