はじめに
ViteとTesting Libraryを使用したテスト環境の構築を学習したため、アウトプット記事を作成します。
手順
1. Viteプロジェクトの開発
以下のコマンド実行後、今回はTypeScriptを選択します。
npm create vite@latest
2. App.tsxを修正
テストをPASSさせるため、以下に修正する。
function App() {
return (
<>
<p>Vite Test</p>
</>
);
}
export default App;
3. テストに必要なパッケージをインストール
npm install --save-dev jest ts-jest @types/jest jest-environment-jsdom@latest @testing-library/react@latest @testing-library/jest-dom@latest @testing-library/user-event@latest ts-node
4. Jest設定ファイルを作成
jest.config.ts
をプロジェクトルートに作成し、次のように設定する。
export default {
preset: 'ts-jest',
testEnvironment: 'jest-environment-jsdom',
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
},
};
5. package.jsonを修正
Jestを実行するために、package.json に以下のコードを追加する。
"scripts": {
"test": "jest"
}
6. tsconfig.jsonを修正
compilerOptions
の部分を追記する。
(compilerOptions
ではTypeScriptコンパイラの動作を制御するためのオプションを指定)
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
],
"compilerOptions": {
"esModuleInterop": true,
"jsx": "react-jsx"
}
}
7. テストファイルの追加
src フォルダ内にテストファイルを追加する。
例えば、App.tsx に対するテストを作成するには、src/App.test.tsx
を作成し、以下のようにテストを記述する。
import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";
import App from "./App";
describe("Sample Test", () => {
test("[Normal]Sample Test", async () => {
// 実行
render(<App />);
// 検証
expect(screen.getByText("Vite Test")).toBeInTheDocument();
});
});
8. テストの実行
テストを実行するために、以下のコマンドを実行する。
npm run test
9. テスト結果の確認
以下のような表示がされればOK!
PASS src/App.test.tsx
Sample Test
✓ [Normal]Sample Test (22 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.587 s, estimated 2 s
Ran all test suites.