効果的な反応コンポーネントテストが重要です。 React Testing Library(RTL)はこのプロセスを簡素化し、ユーザーインタラクションテストを強調します。 この記事では、より効率的で保守可能な単体テストを作成するための5つの高度なRTLテクニックを紹介します。
screen
for queries render()
から直接クエリを破壊することを避けます。 画面
オブジェクトを使用すると、読みやすさと明確さが一貫して向上します。
利点:
例:
の代わりに:
const { getByText } = render();
expect(getByText(/click me/i)).toBeInTheDocument();
使用:
render();
expect(screen.getByText(/click me/i)).toBeInTheDocument();
コンポーネントの場合、要素を非同期に(API呼び出し後)レンダリングすると、 queriesを getby
の代わりに使用します。これにより、アサーションは要素レンダリング後にのみ実行されます。
タイミングの問題により、フレーク状のテストを排除します。
//コンポーネントは、ユーザー名を非同期に取得して表示します render(
// Component asynchronously fetches and displays a username
render( );
const userName = await screen.findByText(/john doe/i);
expect(userName).toBeInTheDocument();
waitfor も同様の結果を達成できますが、 findby
は、 getby
と waitfor
waitfor [waitfor] furanceに適しています。 それらを一緒に使用しないでください。
render( );
await waitFor(() => {
expect(screen.getByText(/john doe/i)).toBeInTheDocument();
});
特定のコンテナ内の要素をターゲティングする場合、ユーティリティ内の曖昧な一致を防ぎます。
意図されていない要素の選択を防ぎます。
与える( ); const namelabel = insin(screen.getByrole( 'Group'))。getByLabelText(/name/i); 想像(namelabel).tobeinthedocument();
render(
);
const nameLabel = within(screen.getByRole('group')).getByLabelText(/Name/i);
expect(nameLabel).toBeInTheDocument();
while はfunctional、 userevent
は、タイピング、クリック、タブなど、より現実的なユーザーインタラクションシミュレーションを提供します。
利点:
より正確なイベントシミュレーション。
'@testing-library/user-event'からusereventをインポートします。
render(
import userEvent from '@testing-library/user-event';
render( );
const emailInput = screen.getByLabelText(/email/i);
const passwordInput = screen.getByLabelText(/password/i);
const submitButton = screen.getByRole('button', { name: /submit/i });
await userEvent.type(emailInput, '[email protected]');
await userEvent.type(passwordInput, 'password123');
await userEvent.click(submitButton);
expect(screen.getByText(/welcome/i)).toBeInTheDocument();
5。
debug()
利点:
は、欠落している要素またはテスト障害をすばやく識別します。
render(
render( );
screen.debug(); // Logs the DOM structure
const section = screen.getByrole( 'region'); 内部(セクション).debug();
const section = screen.getByRole('region');
within(section).debug();
追加のヒント:ユーザーインタラクションに焦点を当ててください:
などの正確なアサーションのようなマッチャーを使用します。
クリーンアップ:
rtlがクリーンアップを処理している間、
jest統合:ターゲットを絞ったテスト実行およびIDE統合カバレッジレポートのためにプラグインを使用してJestを使用することを検討してください。
免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。
Copyright© 2022 湘ICP备2022001581号-3