かもメモ

自分の落ちた落とし穴に何度も落ちる人のメモ帳

jest でパスエイリアスを使いたい

Next.js 製のアプリに React Testing Library と jest でテストを書いていてパスエイリアスでエラーになったので備忘録として

環境

  • Next.js 13.4.12
  • React 18.2.0
  • TypeScript 5.1.6
  • jest 26.6.3
  • @testing-library/jest-dom 5.17.0
  • @testing-library/dom 7.29.2
  • @testing-library/react 14.0.0
  • @testing-library/user-event 14.4.3

Next.js のパスエイリアス

create-next-app でアプリ作成した際に CUI で設定したパスエイリアスが tsconfig に設定されている状態
tsconfig.json

{
  "compilerOptions": {
    "paths": {
      "@/*": ["./src/*"]
    }

パスエイリアスを用いた import がテストでエラーになる

Failed to load "my-page.tsx" file due to Error: Cannot find module '@/components/Layout' from 'src/pages/my-page.tsx'
    > 1 | import { Layout } from '@/components/Layout';

Jest でパスエイリアスを import できるようにする

Jest は tsconfig のパス設定を理解しないので、Jest 用の設定を追加する必要がある
package.json に jest 用の設定を追加するか jest.config.js を作成して、moduleNameMapper にパスエイリアスの指定を追加する

tsconfig で @/*./src/* としているので下記のように設定を追加すれば OK
jest.config.js

module.exports = {
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1"
  }
}

パスエイリアスの指定 1箇所でできるようにしてほしい…


[参考]