メインコンテンツにスキップ
バージョン: v8

ベストプラクティス

テストテンプレートには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のドキュメントを参照してください。