はじめに
TypeScriptのpaths
設定で@/folder
のようにパスを指定した。
テストファイルでもmoduleのimportを@
でパスを設定して、絶対パスで呼び出したい。
// test/Util/DateUtil.test.ts import { dateFactory } from '@/Util/DateUtil'
しかし、そのままテストを実行(例:pnpm test
)すると、Cannot find module '@/Util/DateUtil' from 'test/Util/DateUtil.test.ts'
となる。
先人の情報に感謝しつつ、ここに解決方法を記載する。
先に結論
jest.config.jsのmoduleNameMapper
を設定する。詳細は下記のパスの設定を参照。
環境
- Visual Studio Code 1.82.2
- node 18.18.0
- pnpm 8.7.6
フォルダ構成
. ├── apps │ └── web : coreパッケージを参照するWebアプリ │ └── packages ├── core : 今回対象パッケージ │ ├── src │ │ └── Util │ │ └── DateUtils.ts : テストコードで呼びたいファイル │ ├── test │ │ └── Util │ │ └── DateUtils.test.ts : テスト対象ファイル │ ├── tsconfig.json │ ├── package.json │ └── jest.config.json │ ...他のパッケージ
- モノレポ構成の一部のパッケージ
Jest以外の設定(coreパッケージ内)
{ "devDependencies": { "@types/jest": "29.5.5", "jest": "29.7.0", "ts-jest": "29.1.1", "typescript": "5.2.2" } }
{ "compilerOptions": { "target": "esnext", "module": "nodenext", "composite": false, "moduleResolution": "nodenext", "paths": { "@/*": ["./src/*"] }, "rootDirs": ["./src", "./test"], "declaration": true, "outDir": "./build", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "noImplicitAny": true, "removeComments": true, "noEmit": false, }, "exclude": [ "node_modules", "build" ] }
Jestの設定
今回はJestの導入から始めたので、設定ファイルの作成も記載する。
設定ファイルを作る
- Jestの設定ファイルを作成する
pnpm ts-jest config:init
- 出力ファイル: jest.config.js
/** @type {import("ts-jest/dist/types").InitialOptionsTsJest} */ module.exports = { preset: "ts-jest", testEnvironment: "node", };
パスの設定
jest.config.jsのmoduleNameMapper
を設定する。
pnpm jest
などでテストを実行して、importのエラーがなくれればOK!
/** @type {import('ts-jest').JestConfigWithTsJest} */ module.exports = { preset: 'ts-jest', testEnvironment: 'node', // pathの設定 moduleNameMapper: { "@/(.*)$": "<rootDir>/src/$1" } }