LoginSignup
28
11

More than 3 years have passed since last update.

【Jest】テストファイルからmoduleを絶対パスでimportしたときのエラー: Cannot find module 'src/...' の解決

Last updated at Posted at 2019-03-28

はじめに

ReactでJestを使ったテストを実装したときにmoduleのimportを

hoge.test.tsx
import { Piyo } from 'src/Piyo'

のように、絶対パスで指定してテストを実行するとCannot find module 'src/Piyo' from 'hoge.test.tsx'というエラーが出てしまい解決に時間を要したので共有します。

環境

  • create-react-appで作成したReactプロジェクト
  • node v10.14.1
  • npm v6.9.0
  • yarn v1.12.3
  • TypeScript v3.3.4

解決方法

package.jsonに以下を追記して再度yarn testを実行する

package.json
  "jest": {
    "moduleNameMapper": {
      "src(.*)$": "<rootDir>/src/$1"
    }
  }

これでrootディレクトリ直下の中に入っているsrcフォルダ配下のファイル全てを正しく認識します👏

参考

28
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
11