node.jsreactjsnpmjestjs

Jest gives `Cannot find module` when importing components with absolute paths


Receiving the following error when running Jest

Cannot find module 'src/views/app' from 'index.jsx'

  at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17)
  at Object.<anonymous> (src/index.jsx:4:12)

index.jsx

import AppContainer from 'src/views/app';

package.json

  "jest": {
    "collectCoverageFrom": [
      "src/**/*.{js,jsx,mjs}"
    ],
    "setupFiles": [
      "<rootDir>/config/polyfills.js"
    ],
    "testMatch": [
      "<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
      "<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"
    ],
    "testEnvironment": "node",
    "testURL": "http://localhost",
    "transform": {
      "^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
    ],
    "moduleDirectories": [
        "node_modules",
        "src"
    ],
    "moduleNameMapper": {
      "^react-native$": "react-native-web"
    },
    "moduleFileExtensions": [
      "web.js",
      "js",
      "json",
      "web.jsx",
      "jsx",
      "node",
      "mjs"
    ]
  },

My tests that run files that only contain relative paths in the tree run correctly.

To Clarify, I'm looking for how to configure Jest to not fail on absolute paths.


Solution

  • In package.json you have the below lines of Jest configuration:

    "moduleDirectories": [
        "node_modules",
        "src"
    ]
    

    These says that each module you import will be searched for first in node_modules, then in src.

    Since the code is already looking in the src/, you should use:

    import AppContainer from 'views/app';
    

    Please note that this path is absolute to the src directory, you do not have to navigate to locate it as relative path.

    Or you can configure your root directory in moduleDirectories inside your Jest configuration (in your case, within package.json) so that all your components could be easily found.