「労働者が自分の仕事をうまくやりたいなら、まず自分の道具を研ぎ澄まさなければなりません。」 - 孔子、「論語。陸霊公」
表紙 > プログラミング > あなたのユニットテストを改善するためのReact Testingライブラリのリック

あなたのユニットテストを改善するためのReact Testingライブラリのリック

2025-02-07に投稿しました
ブラウズ:187

ricks for React Testing Library to make your unit tests better

効果的な反応コンポーネントテストが重要です。 React Testing Library(RTL)はこのプロセスを簡素化し、ユーザーインタラクションテストを強調します。 この記事では、より効率的で保守可能な単体テストを作成するための5つの高度なRTLテクニックを紹介します。


1。 screen for queries

を優先する[

render()から直接クエリを破壊することを避けます。 画面オブジェクトを使用すると、読みやすさと明確さが一貫して向上します。

利点:

  • 強化されたテストの読み取り可能性。
  • レンダリングされた画面要素との相互作用を明示的に示しています。

例:

の代わりに:

const { getByText } = render();
expect(getByText(/click me/i)).toBeInTheDocument();

使用:

render();
expect(screen.getByText(/click me/i)).toBeInTheDocument();


2。

findby for aynchronous操作 コンポーネントの場合、要素を非同期に(API呼び出し後)レンダリングすると、

findby

queriesを getby の代わりに使用します。これにより、アサーションは要素レンダリング後にのみ実行されます。

利点:

タイミングの問題により、フレーク状のテストを排除します。
  • は、非同期コンポーネントのより堅牢なテストを作成します。
例:

//コンポーネントは、ユーザー名を非同期に取得して表示します render(); const username = await screen.findbytext(/john doe/i); expect(username).tobeinthedocument();
// 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(); 待機中(()=> { expect(screen.getByText(/john doe/i))。tobeinthedocument(); });
render();
await waitFor(() => {
  expect(screen.getByText(/john doe/i)).toBeInTheDocument();
});

3。

内部の正確なターゲティングのために 特定のコンテナ内の要素をターゲティングする場合、

内の

ユーティリティ内の曖昧な一致を防ぎます。

利点:

意図されていない要素の選択を防ぎます。
  • テスト精度を改善します。
例:

与える(
個人情報 name
); const namelabel = insin(screen.getByrole( 'Group'))。getByLabelText(/name/i); 想像(namelabel).tobeinthedocument();
render(
  
Personal Information
); const nameLabel = within(screen.getByRole('group')).getByLabelText(/Name/i); expect(nameLabel).toBeInTheDocument();


4。

現実的な相互作用のためのuserevent while

fireevent

はfunctional、 userevent は、タイピング、クリック、タブなど、より現実的なユーザーインタラクションシミュレーションを提供します。 利点:

より正確なイベントシミュレーション。

    テキスト入力のような複雑な相互作用を処理します。
  • 例:

'@testing-library/user-event'からusereventをインポートします。 render(); const emailinput = screen.getByLabelText(/email/i); const passwordinput = screen.getByLabelText(/password/i); const submitbutton = screen.getByrole( 'button'、{name: /submit /i}); awevevent.type(emailinput、 '[email protected]'); awevevent.type(passwordinput、 'password123'); awevevent.click(submitbutton); expect(screen.getByText(/welcome/i))。tobeinthedocument();

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()

for dom検査 debug()

メソッドは、DOM構造をコンソールに印刷することにより、テストの障害をトラブルシューティングするために非常に貴重です。

利点:

は、欠落している要素またはテスト障害をすばやく識別します。

    デバッグを簡素化します。
  • 例:

render(); screen.debug(); // dom構造

render();
screen.debug(); // Logs the DOM structure

const section = screen.getByrole( 'region'); 内部(セクション).debug();

const section = screen.getByRole('region');
within(section).debug();
追加のヒント:

ユーザーインタラクションに焦点を当ててください:
    ユーザーが内部コンポーネント状態ではなく、対話するものをテストします。
  • マッチャーを組み合わせます:
  • 。tohavetextcontent()または。tohaveattribute()などの正確なアサーションのようなマッチャーを使用します。 クリーンアップ: rtlがクリーンアップを処理している間、
  • cleanup()
  • in aftereach dom leaksを防ぎます。 jest統合:ターゲットを絞ったテスト実行およびIDE統合カバレッジレポートのためにプラグインを使用してJestを使用することを検討してください。
  • 結論:

RTLは、ユーザー中心のテストに優先順位を付けます。 これらの手法を適用することにより、よりクリーンで信頼性の高い保守可能なテストを作成し、全体的な開発ワークフローを改善します。 これらの戦略を受け入れて、反応テストの実践を強化します。

最新のチュートリアル もっと>

免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。

Copyright© 2022 湘ICP备2022001581号-3