最佳實務
測試範本需要 IonApp
當您在使用 React Testing Library 渲染時,您的測試範本必須使用 IonApp
元件包裹您的元件。這是為了讓元件能夠正確渲染。
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
React Testing Library 建議使用 user-event
函式庫來模擬使用者互動。這個函式庫提供了比 React Testing Library 提供的 fireEvent
函式更真實的使用者互動模擬。
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
的更多資訊,請參閱user-event 文件。