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

Sometimes, we want to fix the ‘Cannot find module’ when importing components with absolute paths with Jest.

In this article, we’ll look at how to fix the ‘Cannot find module’ when importing components with absolute paths with Jest.

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

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.

Conclusion

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