2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Vitest + RTL】Reactアプリをテストする

2
Posted at

はじめに

VitestとRTLでReactアプリをテストしました。テストした内容と躓いたところをまとめます。

テストするReactアプリの概要

テストするのは学習内容と時間を記録する簡易的なアプリです。

画面収録 2026-10-31 17.33.35.gif
以下使用ライブラリ

  • React 19.2.8
  • Vite 8.3.0
  • Node.js 24.22.1
  • Firebase 12.19.0
  • @supabase/supabase-js 2.117.1

テストを行うツール

テストにはVitestとReact Testing Libraryを使用します。
さらにNode.js上でブラウザ環境をエミュレートするjsdom、DOMの状態を検証するマッチャーを追加するjest-dom、ブラウザ上で発生するイベントを検知するuserEventも使用します。

事前準備

テストを行うにあたって必要なライブラリと環境構築をします。

テストライブラリのインストール

プロジェクトのルートディレクトリを開いたら以下のコマンドを実行して必要なものをまとめてインストールしましょう。

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

ちなみにnpm install --save-devは開発環境用のパッケージとしてインストールするコマンドになります。いつもコピペしてたので知らなかった...

インストールが完了したら、package.jsonのdevDependenciesに以下が追加されているか確認しましょう。

"devDependencies": {
  "vitest": "^5.0.5"
  "jsdom": "^30.1.3",
  "@testing-library/dom": "^10.4.2",
  "@testing-library/jest-dom": "^7.0.1",
  "@testing-library/react": "^16.3.3",
}

環境のセットアップ

ライブラリのインストールが完了したら、テストする環境のセットアップを行います。

vite.config.js の設定

vite.config.jsを開いて以下を追記します。

import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";

// https://vite.dev/config/
export default defineConfig({
  plugins: [react()],
+  test: {
+    globals: true, // グローバル変数を有効化
+    environment: "jsdom", // js-domでブラウザ環境をエミュレート
+    setupFiles: './src/test/setup.js', // テスト前にセットアップファイルを実行
+  },
});

globals: trueではVitestのdescribe, it, test, expectなどの各種メソッドをimport無しで使えるようにしています。

environment: "jsdom"でNode.jsの環境にブラウザ環境をエミュレートして、DOMを実行出来るようにしています。

setupFiles: './src/test/setup.js'はインストールしたjest-domのVitestの環境で利用出来るようにセットアップファイルを指定しています。

セットアップファイルを作成したら以下の記述をします。

/src/test/setup.js
import '@testing-library/jest-dom/vitest'

テストを行うファイルで個別にimportしても良いですが、セットアップファイルを指定することでテストを行う前に自動で実行してくれます。

package.json にスクリプトを追加

テストをコマンドで実行出来るようにpackage.jsonにスクリプトを追記します。

{
  "scripts": {
    "test": "vitest",
  }
}

Viteにはインストール時に作成されているpackage.jsonに既にscriptsが書かれているのでそこに追記で問題無いです。

テストを行う

今回のテストで確認するのは以下の内容です。

  • タイトルが表示されていること
  • フォームに学習内容と時間を入力して登録ボタンを押すと新たに記録が追加される
  • 削除ボタンを押すと学習記録が削除される
  • 入力をしないで登録を押すとエラーが表示される

テストを行うAppコンポーネントは以下になります。

App.jsx
import { useState, useEffect } from "react";
import { StudyRecords } from "./components/StudyRecords";
import { AddButton } from "./components/AddButton";
import { DisplayRecords } from "./components/DisplayRecords";
import { InputContents } from "./components/InputContents";
import { InputTime } from "./components/InputTime";
import { getRecords, addRecords, deleteRecords } from "../service/studyRecords";

export const App = () => {
  const [records, setRecords] = useState([]);
  const [loading, setLoading] = useState(true);
  const [contents, setContents] = useState("");
  const [time, setTime] = useState(0);
  const [fetchErrorMessage, setFetchErrorMessage] = useState("");
  const [hasInputError, setHasInputError] = useState(false);

  const handleContentsChange = (e) => {
    setContents(e.target.value);
  };

  const handleTimeChange = (e) => {
    setTime(Number(e.target.value));
  };

  const handleAddRecord = async (contents, time) => {
    if (contents === "" || time === 0) {
      setHasInputError(true);
      return;
    }

    setHasInputError(false);

    try {
      const data = await addRecords(contents, time);
      setRecords(data);
      setContents("");
      setTime(0);
    } catch (error) {
      console.error(error);
      setFetchErrorMessage("データを登録出来ませんでした。ページを更新して再度お試しください。");
    }
  };

  const totalTime = records.reduce((total, record) => {
    return total + record.time;
  }, 0);

  useEffect(() => {
    const fetchTodos = async () => {
      try {
        const data = await getRecords();
        setRecords(data);
      } catch (error) {
        console.error(error);
        setFetchErrorMessage("データを取得出来ませんでした。ページを更新して再度お試しください。");
      } finally {
        setLoading(false);
      }
    };

    fetchTodos();
  }, []);

  const handleDeleteTodo = async (id) => {
    try {
      const data = await deleteRecords(id);
      setRecords(data);
    } catch (error) {
      console.error(error);
      setFetchErrorMessage("データを削除出来ませんでした。ページを更新して再度お試しください。");
    }
  };

  return (
    <div>
      <h1>学習記録一覧</h1>
      <InputContents contents={contents} onChange={handleContentsChange} />
      <InputTime time={time} onChange={handleTimeChange} />
      <DisplayRecords contents={contents} time={time} />
      <AddButton
        contents={contents}
        time={time}
        hasInputError={hasInputError}
        onAdd={handleAddRecord}
      />
      <StudyRecords
        loading={loading}
        fetchErrorMessage={fetchErrorMessage}
        hasInputError={hasInputError}
        records={records}
        totalTime={totalTime}
        onDelete={handleDeleteTodo}
      />
    </div>
  );
};

まずはAppコンポーネントをレンダリングしてアクセス出来るか確認します。

App.test.jsx
import { render, screen } from "@testing-library/react";
import { App } from "./App";

describe("学習記録アプリテスト", () => {
  test("Appコンポーネントのレンダリング確認", () => {
    render(<App />);
    screen.debug();
  });
});

npm run testでテストを実行してターミナルに以下が表示されていればテストは問題無く実行出来ています。
スクリーンショット 2026-11-07 16.11.06.png
render(<App />)の後に書いたscreen.debug()はレンダリングされているDOMをターミナルに表示するRTLのデバッグ用の関数です。

テストを行う際に取得している要素を確認したい場合に使えます。イメージとしてはconsole.logみたいなものです。

Appコンポーネントのレンダリングの確認が出来たのでdescribeの中でテストを書いていきます。なおAppコンポーネントのレンダリングのテストはこの先使用しないため削除しておいてください。

タイトルが表示されていることの確認

このテストではDOMに<h1>学習記録アプリテスト</h1>が存在するかを検証します。

App.test.jsx
import { render, screen, waitFor } from "@testing-library/react";
import { App } from "./App";

describe("学習記録アプリテスト", () => {
 test("h1タイトルの表示確認", async () => {
   render(<App />);

   await waitFor(() => {
      expect(screen.queryByText("データを取得中...")).not.toBeInTheDocument();
   });

   expect(
     screen.getByRole("heading", { level: 1, name: "学習記録一覧" }),
   ).toBeInTheDocument();
  });
 });
});

<h1>学習記録アプリテスト</h1>はコンポーネントに直接書いてあるため、非同期でなくてもテストは通ります。

Appコンポーネントの初回レンダリングの時に非同期でstateを更新している箇所があるため、このstateの更新が完了した後にアサーションを実行しないとテストは成功しているのに警告がターミナルに表示されます。

An update to App inside a test was not wrapped in act(...).

When testing, code that causes React state updates should be wrapped into act(...):

act(() => {
  /* fire events that update state */
});
/* assert on the output */

This ensures that you're testing the behavior the user would see in the browser. Learn more at https://react.dev/link/wrap-tests-with-act

この非同期のstateの更新を行なっているのはAppコンポーネントの以下の記述です。

useEffect(() => {
    const fetchTodos = async () => {
      try {
        const data = await getRecords();
        setRecords(data);
      } catch (error) {
        console.error(error);
        setFetchErrorMessage("データを取得出来ませんでした。ページを更新して再度お試しください。");
      } finally {
        setLoading(false);
      }
    };

    fetchTodos();
  }, []);

try{}ブロックの非同期でstateを更新する処理とfinally{}ブロックのstateの更新が完了したらアサーションを実行したいのでwaitForを使用します。

詳しくは以下の記事で解説しているため参考にしてみてください。

waitFor内のアサーションが完了したら<h1>学習記録アプリテスト</h1>がDOMに存在するかチェックします。

getByRole() はアクセシビリティ上のロールを指定して要素を取得できます。
今回の場合は以下の意味になります。

  • heading:見出し要素(hタグ)
  • level: 1:h1要素
  • name:見出しのテキスト

今回は<h1>学習記録アプリテスト</h1>を取得しています。

toBeInTheDocument()はjest-domのカスタムマッチャーで対象要素がDOMツリーに存在するかを検証します。

<h1>学習記録アプリテスト</h1>がDOMツリーに存在していればテストは成功となります。

フォームに学習内容と時間を入力して登録ボタンを押すと新たに記録が追加される

このテストでは、入力した学習内容と時間でDOMに要素が1つ追加されているかを検証します。

学習内容と学習時間の記録の管理はSupabaseで行なっています。テストを行う際は意図しない副作用の発生やテストの時間の遅延を防ぐために、外部のAPIやDBに接続しません。

これをしないとテスト中にもSupabaseへ学習記録が追加されたり、登録済みの記録を取得してしまい、以下のエラーに苦しむ事になります。

今回のアプリではSupabaseへ接続している関数の処理をモックに差し替えて対応します。モックに差し替えるのはAppコンポーネントからモジュールとしてimportしている以下です。

import { supabase } from "../src/lib/supabaseClient";

// 学習記録の取得
export const getRecords = async () => {
  const { data, error } = await supabase.from("study-record").select();

  if (error) {
    throw error;
  }

  return data;
};

// 学習記録の登録
export const addRecords = async (contents, time) => {
  const { error } = await supabase
    .from("study-record")
    .insert({ time, contents });

  if (error) {
    throw error;
  }

  return await getRecords();
};

// 学習記録の削除
export const deleteRecords = async (id) => {
  await supabase.from("study-record").delete().match({ id });
  return await getRecords();
};

そして以下がテストです。

App.test.jsx
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { getRecords, addRecords, deleteRecords } from "../service/studyRecords";
import { App } from "./App";

 vi.mock("../service/studyRecords", () => ({
  getRecords: vi.fn(),
  addRecords: vi.fn(),
  deleteRecords: vi.fn(),
 }));

describe("学習記録アプリテスト", () => {
// 〜h1のテストは省略〜

 beforeEach(() => {
   vi.clearAllMocks();
   getRecords.mockResolvedValue([]);
 });

 test("フォームに学習内容と時間を入力して登録ボタンを押すと新たに記録が追加される(数が一つ増える)", async () => {
    addRecords.mockImplementation(async (contents, time) => {
      return [{ id: 1, contents, time }];
    });
    render(<App />);
    const user = userEvent.setup();
    const textForm = screen.getByRole("textbox");
    const numForm = screen.getByRole("spinbutton");
    const insertBtn = screen.getByRole("button", { name: "登録" });

    await user.type(textForm, "React");
    await user.type(numForm, "1");
    await user.click(insertBtn);

    const insertElement = await screen.findByText("React:1時間");
    expect(insertElement).toBeInTheDocument();

    const items = await screen.findAllByRole("listitem");
    expect(items).toHaveLength(1);
  });
});

vi.mockの引数にSupabeseへ接続をするモジュールを渡してモックに差し替えます。vi.mock()はファイルやライブラリを丸ごとモックしたい時に利用します。

モックした関数はvi.fn()に置き換えられて、vi.fn()のメソッドが使えるようになります。これで各テストからモックしたモジュールが利用できるようになりました。

各テストでモックしたモジュールを利用するのでbeforeEach()でテストの実行前にモックの履歴をリセットします。さらに、アプリではレンダリングの度にgetRecords()でSupabaseへ接続して学習記録の取得を行なっているのでこちらをモックして空の配列を返しています。

これでテストに必要な準備が全て整いました。

test("フォームに学習内容と時間を入力して登録ボタンを押すと新たに記録が追加される(数が一つ増える)", async () => {
    addRecords.mockImplementation(async (contents, time) => {
      return [{ id: 1, contents, time }];
    });
    render(<App />);
    const user = userEvent.setup();
    const textForm = screen.getByRole("textbox");
    const numForm = screen.getByRole("spinbutton");
    const insertBtn = screen.getByRole("button", { name: "登録" });

    await user.type(textForm, "React");
    await user.type(numForm, "1");
    await user.click(insertBtn);

    const insertElement = await screen.findByText("React:1時間");
    expect(insertElement).toBeInTheDocument();

    const items = await screen.findAllByRole("listitem");
    expect(items).toHaveLength(1);
  });

テストの冒頭でモックしたaddRecordsの戻り値を設定します。id:1は固定で、contentsとtimeはアプリの挙動と同様にフォームに入力された値を設定したいのでAppコンポーネントで使用しているstateを使います。

今回は入力フォームとボタンのテストを行いたいのでuserEventを利用します。userEventはRTLのメソッドで、クリック・ホバー・キー入力・フォーカスといったブラウザで発生する挙動をテストで再現します。

今回は学習内容にReact、学習時間は1時間が入力された想定でテストを行います。

await user.type(textForm, "React");
await user.type(numForm, "1");

ボタンクリックでaddRecordsが実行されて、入力したReactと1がstateに渡っていきます。

const insertElement = await screen.findByText("React:1時間");
expect(insertElement).toBeInTheDocument();

このテストでは「React:1時間」のテキストを持つ要素がDOMに存在するかをチェックしています。

const items = await screen.findAllByRole("listitem");
expect(items).toHaveLength(1);

このテストでは、li要素が1つ存在しているかをチェックしています。「React:1時間」はli要素として追加しているため、要素の追加が完了していれば<li>React:1時間</li>がDOMに1つ存在しているはずです。

このテストでは、Supabaseへの接続処理をモックに差し替えた事によってDOMのみに要素を追加出来るようになりました。

削除ボタンを押すと学習記録が削除される

このテストでは学習記録がDOMから削除出来るかを検証します。

App.test.jsx
describe("学習記録アプリテスト", () => {
  test("削除ボタンを押すと学習記録が削除される(数が1つ減る)", async () => {
    getRecords.mockResolvedValue([{ id: 1, contents: "React", time: 1 }]);
    deleteRecords.mockResolvedValue([]);
    render(<App />);

    const user = userEvent.setup();
    expect(await screen.findAllByRole("listitem")).toHaveLength(1);

    await user.click(await screen.findByRole("button", { name: "削除" }));

    expect(deleteRecords).toHaveBeenCalledWith(1);

    await waitFor(() => {
      expect(screen.queryAllByRole("listitem")).toHaveLength(0);
    });
  });

beforeEach()の中でgetRecords()の戻り値を空の配列にしているため、テスト開始時点で削除対象の要素はDOMに存在していません。

そのためこのテストの中でgetRecordsの引数に削除データを追加して、削除データが1件ある状態でAppコンポーネントをレンダリングします。[{ id: 1, contents: "React", time: 1 }]で削除テスト用の学習記録が追加されます。

expect(await screen.findAllByRole("listitem")).toHaveLength(1);

このテストで削除用の学習記録がテストに存在しているかをチェックしています。このテストが問題なければ、学習記録が1件ある状態となります。

削除データが準備できたら本題の削除ボタンをクリックしたら学習記録が削除されているかをテストします。

await user.click(await screen.findByRole("button", { name: "削除" }));
expect(deleteRecords).toHaveBeenCalledWith(1);

削除ボタンがクリックされた時に引数1でdeleteRecordsが実行されているかを検証します。引数1は削除用の学習記録のidです。

アプリ側では学習記録のidでSupabaseから学習記録の削除を行なっているのでテストでもSupabaseへの接続をモックしつつそれを再現しています。

await waitFor(() => {
  expect(screen.queryAllByRole("listitem")).toHaveLength(0);
});

最後に非同期でli要素がDOMから削除されるのを検証し、PASSしたら削除ボタンで学習記録を削除するテストは完了です。

入力をしないで登録を押すとエラーが表示される

学習内容と学習時間を入力せずに登録ボタンを押したらエラーが表示されるかをテストします。このテストは3つのエラーパターンがあります。

  • 学習内容と学習時間が入力されていない
  • 学習内容が入力されていない
  • 学習時間が入力されていない

1つのテストでは1つの条件を確かめるのが基本なので3パターンのテストを行います。

App.test.jsx
describe("学習記録アプリテスト", () => {
  // 解説済みのテストは省略
  describe("入力エラーテスト", () => {
    test("学習内容と学習時間を入力せずに登録を押すとエラーが表示されるか", async () => {
      render(<App />);

      const user = userEvent.setup();

      expect(
        screen.queryByText("未入力の項目があります"),
      ).not.toBeInTheDocument();

      await user.click(screen.getByRole("button", { name: "登録" }));

      expect(screen.getByText("未入力の項目があります")).toBeInTheDocument();
      expect(addRecords).not.toHaveBeenCalled();
    });

    test("学習内容のみを入力して登録を押すとエラーが表示されるか", async () => {
      render(<App />);

      const user = userEvent.setup();

      expect(
        screen.queryByText("未入力の項目があります"),
      ).not.toBeInTheDocument();

      await user.type(screen.getByRole("textbox"), "React");
      await user.click(screen.getByRole("button", { name: "登録" }));

      expect(screen.getByText("未入力の項目があります")).toBeInTheDocument();
      expect(addRecords).not.toHaveBeenCalled();
    });

    test("学習時間のみを入力して登録を押すとエラーが表示されるか", async () => {
      render(<App />);

      const user = userEvent.setup();

      expect(
        screen.queryByText("未入力の項目があります"),
      ).not.toBeInTheDocument();

      await user.type(screen.getByRole("spinbutton"), "1");
      await user.click(screen.getByRole("button", { name: "登録" }));

      expect(screen.getByText("未入力の項目があります")).toBeInTheDocument();
      expect(addRecords).not.toHaveBeenCalled();
    });
  });
});

テストは3つに分けていますが、エラーチェックという内容で共通しているのでdescribeでグループ化しています。

3つのテストに共通することとして、登録ボタンクリックの前にエラー文が表示されていないことを確認しています。

expect(screen.queryByText("未入力の項目があります")).not.toBeInTheDocument();

このテストは入力不足がある状態でボタンをクリックしたらエラー文が表示されているかを検証するのが目的なので、最初からエラー文が表示されている状態でないかをチェックしています。

このテストが通らないと、テストを想定している挙動とは異なってしまうためその確認のために入れているというイメージです。

最後に入力不足がある状態で登録ボタンがクリックされた時にエラー文が表示されているかと登録処理が動いていないかをテストしています。

expect(screen.getByText("未入力の項目があります")).toBeInTheDocument();
expect(addRecords).not.toHaveBeenCalled();

登録処理についてはアプリ側で条件分岐とエラーの状態をstateで管理して対応していますが、それが機能しているかも含めてのテストになります。

これでテストは完了になります。
以下が最終的なテストのコードになります。

App.test.jsx
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { getRecords, addRecords, deleteRecords } from "../service/studyRecords";
import { App } from "./App";

vi.mock("../service/studyRecords", () => ({
  getRecords: vi.fn(),
  addRecords: vi.fn(),
  deleteRecords: vi.fn(),
}));

describe("学習記録アプリテスト", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    getRecords.mockResolvedValue([]);
  });

  test("h1タイトルの表示確認", async () => {
    render(<App />);

    await waitFor(() => {
      expect(screen.queryByText("データを取得中...")).not.toBeInTheDocument();
    });

    expect(
      screen.getByRole("heading", { level: 1, name: "学習記録一覧" }),
    ).toBeInTheDocument();
  });

  test("フォームに学習内容と時間を入力して登録ボタンを押すと新たに記録が追加される(数が一つ増える)", async () => {
    addRecords.mockImplementation(async (contents, time) => {
      return [{ id: 1, contents, time }];
    });
    render(<App />);
    const user = userEvent.setup();
    const textForm = screen.getByRole("textbox");
    const numForm = screen.getByRole("spinbutton");
    const insertBtn = screen.getByRole("button", { name: "登録" });

    await user.type(textForm, "React");
    await user.type(numForm, "1");
    await user.click(insertBtn);

    const insertElement = await screen.findByText("React:1時間");
    expect(insertElement).toBeInTheDocument();

    const items = await screen.findAllByRole("listitem");
    expect(items).toHaveLength(1);
  });

  test("削除ボタンを押すと学習記録が削除される(数が1つ減る)", async () => {
    getRecords.mockResolvedValue([{ id: 1, contents: "React", time: 1 }]);
    deleteRecords.mockResolvedValue([]);
    render(<App />);

    const user = userEvent.setup();
    expect(await screen.findAllByRole("listitem")).toHaveLength(1);

    await user.click(await screen.findByRole("button", { name: "削除" }));

    expect(deleteRecords).toHaveBeenCalledWith(1);

    await waitFor(() => {
      expect(screen.queryAllByRole("listitem")).toHaveLength(0);
    });
  });

  describe("入力エラーテスト", () => {
    test("学習内容と学習時間を入力せずに登録を押すとエラーが表示されるか", async () => {
      render(<App />);

      const user = userEvent.setup();

      expect(
        screen.queryByText("未入力の項目があります"),
      ).not.toBeInTheDocument();

      await user.click(screen.getByRole("button", { name: "登録" }));

      expect(screen.getByText("未入力の項目があります")).toBeInTheDocument();
      expect(addRecords).not.toHaveBeenCalled();
    });

    test("学習内容のみを入力して登録を押すとエラーが表示されるか", async () => {
      render(<App />);

      const user = userEvent.setup();

      expect(
        screen.queryByText("未入力の項目があります"),
      ).not.toBeInTheDocument();

      await user.type(screen.getByRole("textbox"), "React");
      await user.click(screen.getByRole("button", { name: "登録" }));

      expect(screen.getByText("未入力の項目があります")).toBeInTheDocument();
      expect(addRecords).not.toHaveBeenCalled();
    });

    test("学習時間のみを入力して登録を押すとエラーが表示されるか", async () => {
      render(<App />);

      const user = userEvent.setup();

      expect(
        screen.queryByText("未入力の項目があります"),
      ).not.toBeInTheDocument();

      await user.type(screen.getByRole("spinbutton"), "1");
      await user.click(screen.getByRole("button", { name: "登録" }));

      expect(screen.getByText("未入力の項目があります")).toBeInTheDocument();
      expect(addRecords).not.toHaveBeenCalled();
    });
  });
});

おわりに

小規模なアプリでもテストする項目が多く、結構苦戦しました。どこまでをテストで確認するのかの切り分けの判断が出来るようにもっとテストへの理解度を上げていきたいです。

参考

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?