跳至主要內容
版本:v8

範例

測試由觸發器呈現的模態框

此範例展示如何測試由觸發器呈現的模態框。當使用者點擊按鈕時,會呈現模態框。

範例元件

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 hook 呈現的模態框。當使用者點擊按鈕時,會呈現模態框。

範例元件

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();
});
});