Categories
JavaScript Answers

How to fix the ‘Cannot find module’ when importing components with absolute paths with Jest?

Spread the love

To fix the ‘Cannot find module’ when importing components with absolute paths with Jest, we can set the roots setting of the Jest config.

For instance, we write

"jest": {
  "roots": [
    "<rootDir>",
    "/home/some/path/"
  ],
  "modulePaths": [
    "<rootDir>",
    "/home/some/other/path"
  ],
  "moduleDirectories": [
    "node_modules"
  ],
}

to add the '<rootDir>' and "/home/some/path/" path strings into the roots array.

This makes these 2 paths the root path when we use absolute imports.

Likewise, we add the same entries to modulePaths to add them as root paths for absolute imports.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *