Skip to main content

最佳实践

¥Best Practices

测试模板需要 IonApp

¥IonApp is required for test templates

在使用 React 测试库渲染时的测试模板中,你必须使用 IonApp 组件封装你的组件。这是正确渲染组件所必需的。

¥In your test template when rendering with React Testing Library, you must wrap your component with an IonApp component. This is required for the component to be rendered correctly.

Example.test.tsx


import { IonApp } from '@ionic/react';


import { render } from "@testing-library/react";

import Example from './Example';

test('example', () => {
render(
<IonApp>
<Example />
</IonApp>
);
...
});

使用 user-event 进行用户交互

¥Use user-event for user interactions

React 测试库建议使用 user-event 库来模拟用户交互。该库提供了比 React 测试库提供的 fireEvent 函数更真实的用户交互模拟。

¥React Testing Library recommends using the user-event library for simulating user interactions. This library provides a more realistic simulation of user interactions than the fireEvent function provided by React Testing Library.

Example.test.tsx


import { IonApp } from '@ionic/react';




import { render } from '@testing-library/react';




import userEvent from '@testing-library/user-event';



import Example from './Example';

test('example', async () => {
const user = userEvent.setup();

render(
<IonApp>
<Example />
</IonApp>
);

await user.click(screen.getByRole('button', { name: /click me!/i }));
});

有关 user-event 的更多信息,请参阅 用户事件文档

¥For more information on user-event, see the user-event documentation.