テストの実行方法(Jest + React Testing Library)
React アプリで Jest と React Testing Library を使ってテストを実行するには、以下のステップで行います。
📦 必要なパッケージのインストール(初回のみ)
npm install --save-dev jest @testing-library/react @testing-library/jest-dom @testing-library/user-event
CRA(Create React App)を使用している場合は、すでにインストール済みの場合があります。
🛠 package.json にテストスクリプトを定義(CRAなら既にある)
{
"scripts": {
"test": "react-scripts test"
}
}
もしくは、自前の Jest を使う場合は:
{
"scripts": {
"test": "jest"
}
}
▶️ テストの実行(全体)
npm test
# または
yarn test
- 対話モード(watchモード)で起動
a
を押すとすべてのテストが再実行される
📁 特定ファイルだけをテストする
npm test GreetingForm
ファイル名やコンポーネント名の一部でもOK(インクリメンタル検索)
🧪 CI/CD などで1回だけ実行したい場合(非対話)
npm test -- --watchAll=false
✅ テストファイルの命名規則(Jest)
*.test.tsx
/*.test.js
__tests__
ディレクトリ配下に配置- Jest はこれらを自動で検出します
🔧 Jestの設定をカスタマイズする場合(任意)
// jest.config.js
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['
<rootDir>/src/setupTests.ts'],
moduleNameMapper: {
'^@/(.*)$': '
<rootDir>/src/$1'
},
}
🧩 テスト環境の前処理
// src/setupTests.ts
import '@testing-library/jest-dom'
✅ よくあるトラブルと対処法
問題 | 解決策 |
---|---|
expect(...).toBeInTheDocument is not a function |
@testing-library/jest-dom が import されていない |
ReferenceError: fetch is not defined |
whatwg-fetch や msw を使ってモックを追加 |
Jest encountered an unexpected token |
Babel 設定 or ESM/CJS の互換性に注意 |
🔗 参考リンク