ホームページ ウェブフロントエンド jsチュートリアル Vitest を使用した React アプリケーションのテスト: 包括的なガイド

Vitest を使用した React アプリケーションのテスト: 包括的なガイド

Aug 28, 2024 am 06:01 AM

Testing React Applications with Vitest: A Comprehensive Guide

テストは最新のソフトウェア開発の重要な側面であり、コードが期待どおりに動作することを確認し、アプリケーションの進化に伴う回帰を防ぎます。 React エコシステムでは、Vitest などのツールが、最新の React アプリケーションとシームレスに統合される、高速かつ強力で使いやすいテスト フレームワークを提供します。この投稿では、Vitest をセットアップして使用して、React コンポーネント、フック、ユーティリティを効果的にテストする方法を説明します。


1. ヴィテストの紹介

Vitest は、最新の JavaScript および TypeScript プロジェクト、特にビルド ツールとして Vite を使用するプロジェクト向けに構築された超高速のテスト フレームワークです。 Vitest は、React コミュニティで最も人気のあるテスト フレームワークの 1 つである Jest からインスピレーションを得ていますが、速度とシンプルさのために最適化されているため、Vite を利用した React プロジェクトに最適です。

主な特徴:

  • 高速実行: Vitest はテストを並行して実行し、Vite の高速ビルド機能を活用します。
  • ネイティブ ESM サポート: Vitest は最新の JavaScript 向けに設計されており、すぐに使える ES モジュールのサポートを提供します。
  • Jest との互換性: Jest に慣れている場合は、Vitest の API に馴染みがあり、移行がスムーズになるでしょう。
  • 組み込みの TypeScript サポート: Vitest は TypeScript をネイティブにサポートし、テストでタイプ セーフティを提供します。

2. React プロジェクトでの Vitest のセットアップ

React プロジェクトで Vitest をセットアップすることから始めましょう。 Vite を使用して React アプリを作成したと仮定します。そうでない場合は、次のコマンドを使用してすぐに作成できます:

1

2

npm create vite@latest my-react-app -- --template react

cd my-react-app

ログイン後にコピー

ステップ 1: Vitest と関連する依存関係をインストールする

Vitest を React Testing Library およびその他の必要な依存関係とともにインストールします。

1

npm install --save-dev vitest @testing-library/react @testing-library/jest-dom @testing-library/user-event

ログイン後にコピー
  • vitest: テスト フレームワーク。
  • @testing-library/react: React コンポーネントをテストするためのユーティリティを提供します。
  • @testing-library/jest-dom: DOM ノード アサーション用のカスタム マッチャーを Jest と Vitest に追加します。
  • @testing-library/user-even: DOM とのユーザー操作をシミュレートします。

ステップ 2: Vitest を構成する

次に、プロジェクトのルートで vitest.config.ts ファイルを作成または変更して、Vitest を構成します。

1

2

3

4

5

6

7

8

9

10

11

import { defineConfig } from 'vitest/config';

import react from '@vitejs/plugin-react';

 

export default defineConfig({

  plugins: [react()],

  test: {

    environment: 'jsdom',

    globals: true,

    setupFiles: './src/setupTests.ts',

  },

});

ログイン後にコピー
  • 環境: 'jsdom': テスト用にブラウザ環境をモックします。
  • globals: true: インポートせずに、describe、it、expect などのグローバル変数を使用できるようにします。
  • setupFiles: Jest の setupFilesAfterEnv に似た、テスト構成をセットアップするためのファイル。

ステップ 3: セットアップ ファイルを作成する

src ディレクトリに setupTests.ts ファイルを作成して、@testing-library/jest-dom を構成します。

1

import '@testing-library/jest-dom';

ログイン後にコピー

このセットアップでは、jest-dom によって提供されるカスタム マッチャーがテストに自動的に組み込まれます。


3. React コンポーネントのテストの作成

Vitest をセットアップしたら、単純な React コンポーネント用のテストをいくつか書いてみましょう。次の Button コンポーネントについて考えてみましょう:

1

2

3

4

5

6

7

8

9

10

11

12

13

// src/components/Button.tsx

import React from 'react';

 

type ButtonProps = {

  label: string;

  onClick: () => void;

};

 

const Button: React.FC<ButtonProps> = ({ label, onClick }) => {

  return <button onClick={onClick}>{label}</button>;

};

 

export default Button;

ログイン後にコピー

次に、このコンポーネントのテストを作成しましょう:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

// src/components/Button.test.tsx

import { render, screen } from '@testing-library/react';

import userEvent from '@testing-library/user-event';

import Button from './Button';

 

describe('Button Component', () => {

  it('renders the button with the correct label', () => {

    render(<Button label="Click Me" onClick={() => {}} />);

    expect(screen.getByText('Click Me')).toBeInTheDocument();

  });

 

  it('calls the onClick handler when clicked', async () => {

    const handleClick = vi.fn();

    render(<Button label="Click Me" onClick={handleClick} />);

    await userEvent.click(screen.getByText('Click Me'));

    expect(handleClick).toHaveBeenCalledTimes(1);

  });

});

ログイン後にコピー

説明:

  • render: テスト用にコンポーネントをレンダリングします。
  • 画面: レンダリングされた DOM をクエリします。
  • userEvent.click: ボタンのクリック イベントをシミュレートします。
  • vi.fn(): 関数をモックしてその呼び出しを追跡します。

4. テストの実行

次のコマンドを使用してテストを実行できます:

1

npx vitest

ログイン後にコピー

これにより、デフォルトでパターン *.test.tsx または *.spec.tsx に従うすべてのテスト ファイルが実行されます。以下を使用して監視モードでテストを実行することもできます:

1

npx vitest --watch

ログイン後にコピー

Vitest は詳細な出力を提供し、各テストのステータスと発生したエラーを示します。


5. フックとカスタム ユーティリティのテスト

Vitest は、カスタム React フックとユーティリティのテストにも使用できます。カスタムフック useCounter:
があるとします。

1

2

3

4

5

6

7

8

9

10

11

// src/hooks/useCounter.ts

import { useState } from 'react';

 

export function useCounter(initialValue = 0) {

  const [count, setCount] = useState(initialValue);

 

  const increment = () => setCount((prev) => prev + 1);

  const decrement = () => setCount((prev) => prev - 1);

 

  return { count, increment, decrement };

}

ログイン後にコピー

このフックのテストは次のように作成できます:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

// src/hooks/useCounter.test.ts

import { renderHook, act } from '@testing-library/react-hooks';

import { useCounter } from './useCounter';

 

describe('useCounter Hook', () => {

  it('initializes with the correct value', () => {

    const { result } = renderHook(() => useCounter(10));

    expect(result.current.count).toBe(10);

  });

 

  it('increments the counter', () => {

    const { result } = renderHook(() => useCounter());

    act(() => {

      result.current.increment();

    });

    expect(result.current.count).toBe(1);

  });

 

  it('decrements the counter', () => {

    const { result } = renderHook(() => useCounter(10));

    act(() => {

      result.current.decrement();

    });

    expect(result.current.count).toBe(9);

  });

});

ログイン後にコピー

説明:

  • renderHook: テスト環境で React フックをレンダリングします。
  • act: アサーションを行う前に、状態または効果への更新が確実に処理されるようにします。

6. 結論

Vitest は、特に Vite のような最新のツールと組み合わせた場合に、React アプリケーションをテストするための強力かつ効率的な方法を提供します。そのシンプルさ、スピード、既存の Jest プラクティスとの互換性により、小規模および大規模な React プロジェクトにとって優れた選択肢となります。

By integrating Vitest into your workflow, you can ensure that your React components, hooks, and utilities are thoroughly tested, leading to more robust and reliable applications. Whether you’re testing simple components or complex hooks, Vitest offers the tools you need to write effective tests quickly.

For more information, visit the Vitest documentation.

Feel free to explore more advanced features of Vitest, such as mocking, snapshot testing, and parallel test execution, to further enhance your testing capabilities.

1

Happy Coding ?‍?

ログイン後にコピー

以上がVitest を使用した React アプリケーションのテスト: 包括的なガイドの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットな記事タグ

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

JavaScriptの文字列文字を交換します JavaScriptの文字列文字を交換します Mar 11, 2025 am 12:07 AM

JavaScriptの文字列文字を交換します

jQuery日付が有効かどうかを確認します jQuery日付が有効かどうかを確認します Mar 01, 2025 am 08:51 AM

jQuery日付が有効かどうかを確認します

jQueryは要素のパディング/マージンを取得します jQueryは要素のパディング/マージンを取得します Mar 01, 2025 am 08:53 AM

jQueryは要素のパディング/マージンを取得します

10 jQuery Accordionsタブ 10 jQuery Accordionsタブ Mar 01, 2025 am 01:34 AM

10 jQuery Accordionsタブ

10 jqueryプラグインをチェックする価値があります 10 jqueryプラグインをチェックする価値があります Mar 01, 2025 am 01:29 AM

10 jqueryプラグインをチェックする価値があります

ノードとHTTPコンソールを使用したHTTPデバッグ ノードとHTTPコンソールを使用したHTTPデバッグ Mar 01, 2025 am 01:37 AM

ノードとHTTPコンソールを使用したHTTPデバッグ

jQueryはscrollbarをdivに追加します jQueryはscrollbarをdivに追加します Mar 01, 2025 am 01:30 AM

jQueryはscrollbarをdivに追加します

カスタムGoogle検索APIセットアップチュートリアル カスタムGoogle検索APIセットアップチュートリアル Mar 04, 2025 am 01:06 AM

カスタムGoogle検索APIセットアップチュートリアル

See all articles