react で テストを jest or vitest で比較してみる

● A. react + typescript + jest アプリでテストを実行する

アプリの初期化

npx create-react-app react-jest-app --template typescript

その他パッケージのインストール

npm install recoil @types/recoil
npm install -D jest @types/jest ts-jest 
npm install -D @babel/preset-react
npm install -D @testing-library/react

アプリの作成

(割愛します。ボタンをクリックすると数字が1つずつ増えていくボタンとそれをRecoilを通して表示すると言う簡単なアプリです)

app.test.tsx を作成して実行する

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

describe("App.tsx", () => {
  test("アプリをマウントすると Counterに「ボタン 0」が表示される", () => {
    render(<App />);
    expect(screen.getByRole("button").innerHTML).toEqual("ボタン 0");
  });

  test("アプリをマウントすると Viewerに「表示 0」が表示される", () => {
    render(<App />);
    expect(screen.getByTestId("viewer-count-value").innerHTML).toEqual(
      "表示 0"
    );
  });

  test("ボタンをクリックすると 「ボタン 1」に表示が変わる", async () => {
    render(<App />);
    const button = screen.getByRole("button");
    await fireEvent.click(button);
    // console.log(button.innerHTML);
    expect(screen.getByRole("button").innerHTML).toEqual("ボタン 1");
  });

  test("ボタンを5回クリックすると 「ボタン 5」に表示が変わる", async () => {
    render(<App />);
    const button = screen.getByRole("button");

    await fireEvent.click(button);
    await fireEvent.click(button);
    await fireEvent.click(button);
    await fireEvent.click(button);
    await fireEvent.click(button);

    expect(screen.getByRole("button").innerHTML).toEqual("ボタン 5");
  });
});

テストの実行

npx react-scripts test 

● B. react + typescript + vite + vitest + happy-dom アプリでテストを実行する

アプリの初期化

(react を選択してから、react-tsを選択します)

npm init vite@latest react-vitest-app

その他パッケージのインストール

npm install recoil @types/recoil
npm install -D vitest
npm install -D @testing-library/react
npm install happy-dom

vitest 用に vite.config.ts を変更

vite.config.ts

/// <reference types="vitest" />

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

// https://vitejs.dev/config/

export default defineConfig({
  plugins: [react()],
  test: {
    environment: 'happy-dom',
  },
})

テストの実行

npx vitest --reporter verbose

参考 : https://bit.ly/3JuAaPV
参考 : https://dev.classmethod.jp/articles/intro-vitest/

● jest , vitest の違いについて

vitestの場合

  afterEach(() => {
    cleanup();
  })

を実行して、

    render(<App />);

を毎回初期化する必要があるようです。

速度について

速度についてはテストケースが少ない場合はさほど違いはありませんがvitestの方が若干早いです

No.2197
08/31 21:51

edit