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
(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
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/
afterEach(() => {
cleanup();
})
を実行して、
render(<App />);
を毎回初期化する必要があるようです。
速度についてはテストケースが少ない場合はさほど違いはありませんがvitestの方が若干早いです