Skip to main content

示例

¥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';



export default function Example() {
return (
<>
<IonButton id="open-modal">Open</IonButton>
<IonModal trigger="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';



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 渲染的模式

¥Testing a modal presented from useIonModal

此示例演示如何测试使用 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';



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;

测试模态

¥Testing the modal

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