Best Practices
IonApp is required for test templates
React Testing Library を使用してテストテンプレートをレンダリングする際には、コンポーネントをIonAppコンポーネントで囲む必要があります。これは、コンポーネントが正しくレンダリングされるための必須の処理です。
Example.test.tsx
import { IonApp } from '@ionic/react';
import { render } from '@testing-library/react';
import { test } from 'vitest';
import Example from './Example';
test('example', () => {
render(
<IonApp>
<Example />
</IonApp>
);
...
});
Use user-event for user interactions
React Testing Library は、ユーザー操作のシミュレーションに user-event ライブラリを推奨しています。React Testing Library が提供する fireEvent 関数よりも実際の操作に近い動作を再現できます。
Example.test.tsx
import { IonApp } from '@ionic/react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { test } from 'vitest';
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 documentationを参照してください。
コンポーネントの待機
Ionic コンポーネントがレンダリングされるのを待ってからその DOM に対してアサートする必要がある場合は、@ionic/coreからエクスポートされるcomponentOnReadyヘルパーを使用してください。el.componentOnReady()を直接呼び出さないでください。@ionic/reactは Stencil の Custom Element ビルドを使用しており、そのメソッドは要素上に存在しません。ヘルパーは代わりに 1 フレーム待機し、コンポーネントの内部コンテンツがレンダリングされる機会を与えます。
import { componentOnReady } from '@ionic/core';
import { IonApp } from '@ionic/react';
import { render } from '@testing-library/react';
import { expect, test } from 'vitest';
import Example from './Example';
test('renders the submit button', async () => {
const { container } = render(
<IonApp>
<Example />
</IonApp>
);
const button = container.querySelector('ion-button')!;
await new Promise<void>((resolve) => componentOnReady(button, () => resolve()));
expect(button.textContent).toContain('Submit');
});