Jest: Cannot find module
Jestでモジュールが見つからない場合のエラー原因と解決策
概要
Jestでテスト実行時にモジュールの解決に失敗するエラーです。
エラーメッセージ
``` Cannot find module ‘@/components/Button’ from ‘src/App.test.tsx’ ```
原因
- パスエイリアスの未設定: @/ 等のエイリアスがJestで未認識
- モジュールのモック不足: 外部モジュールのモック必要
- ESM/CJSの不整合: ES Modulesの処理問題
- node_modulesの変換除外: transformIgnorePatternsの設定
解決策
1. パスエイリアスを設定
```javascript // jest.config.js module.exports = { moduleNameMapper: { ‘^@/(.)$’: ‘/src/$1’, ‘^@components/(.)$’: ‘/src/components/$1’, }, }; ```
2. TypeScript paths と同期
```json // tsconfig.json { “compilerOptions”: { “baseUrl”: “.”, “paths”: { “@/”: [“src/”] } } } ```
```javascript // jest.config.js (ts-jest使用時) const { pathsToModuleNameMapper } = require(’ts-jest’); const { compilerOptions } = require(’./tsconfig.json’);
module.exports = { preset: ’ts-jest’, moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: ‘/’ }), }; ```
3. 静的アセットをモック
```javascript // jest.config.js module.exports = { moduleNameMapper: { ‘\.(css|less|scss|sass)$’: ‘identity-obj-proxy’, ‘\.(jpg|jpeg|png|gif|svg)$’: ‘/mocks/fileMock.js’, }, };
// mocks/fileMock.js module.exports = ’test-file-stub’; ```
4. ESMパッケージを変換
```javascript // jest.config.js module.exports = { transformIgnorePatterns: [ ’node_modules/(?!(axios|uuid|nanoid)/)’, // これらは変換する ], }; ```
5. モジュールをモック
```javascript // mocks/next/router.js module.exports = { useRouter: () => ({ push: jest.fn(), pathname: ‘/’, query: {}, }), }; ```
よくある間違い
- tsconfig.json と jest.config.js のパス設定不一致
- node_modules内のESMモジュールを変換しない
- モックファイルの配置場所
関連エラー
関連エラー
Testing の他のエラー
この記事は役に立ちましたか?