LoginSignup
39
26

More than 5 years have passed since last update.

Jestでaliasなパスでmoduleをimportできるように

Last updated at Posted at 2017-08-01

問題

Webpack.resolve.aliastsconfigpathsなんかでエイリアスを設定していて、そのソースをJestでテストしようとすると、Jestにそんなモジュールないよと怒られてしまいます。なので、Jestでもエイリアス設定するやり方。

設定

package.jsonjest.moduleNameMapperを設定します。

Jest - moduleNameMapper

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

キーが正規表現、右がエイリアス。jsのreplaceみたいな感じですね。

"components/button".replace(new RegExp("^components/(.+)"), "<rootDir>/src/components/$1")
// <rootDir>/src/components/button

<rootDir>

これは現在ディレクトリにpackage.jsonがあるなら現在のディレクトリないならprocess.cwd()のパスが入ります。

39
26
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
39
26