LoginSignup
2
0

vite+react+testing-libraryでのコンポーネントテストの環境構築方法

Posted at

はじめに

vite+react+testing-libraryで、コンポーネントテストの環境構築の方法をご紹介します。

環境

nodeのバージョンです。

node -v
v20.11.0

モジュールは以下のバージョンで確認しています。

"@testing-library/react": "^14.2.1",
"vitest": "^1.3.1"

環境構築

viteの最新版でプロジェクトを生成します。

npm init vite@latest

設定は以下の通りです。

✔ Project name: … vite-project
✔ Select a framework: › React
✔ Select a variant: › TypeScript

作業ディレクトリを移動して、モジュールをインストールします。

cd vite-project
npm install

テストで必要なモジュールをインストールします。

npm install --save-dev vitest jsdom @testing-library/react

package.jsonファイルのscriptsに以下を追加します。

package.json
"test": "vitest"

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: 'jsdom'
+  }
 })

src/App.test.tsxファイルを作成して、以下コードを追加します。

screen.debug();で描画するHTMLを出力します。

src/App.test.tsx
import { describe, it }from 'vitest'
import { render, screen } from '@testing-library/react'
import App from './App'

describe('App', () => {
  it('sample test', () => {
    render(<App />)

    screen.debug();
  })
})

テストを実行します。

npm run test

以下のように出力されれば成功です。🎉

 ✓ src/App.test.tsx (1)
   ✓ App (1)
     ✓ sample test

 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  22:00:57
   Duration  341ms (transform 22ms, setup 0ms, collect 79ms, tests 17ms, environment 143ms, prepare 31ms)

まとめ

vite+react+testing-libraryで、コンポーネントテストの環境構築の方法をご紹介しました。今回はやりませんでしたが、ユーザーイベント(クリックなど)を発火するにはこちらのインストールが必要です。気になる方は試してみてください。

最後に

GoQSystemでは一緒に働いてくれる仲間を募集中です!

ご興味がある方は以下リンクよりご確認ください。

2
0
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
0