173

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.

Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
  • try `import AppContainer from './src/views/app';` – Metalik Jun 14 '18 at 17:59
  • 11
    I need to know how to run absolute paths so I don't have to back step multiple directories on imports or update as many files if I move files – Seth McClaine Jun 14 '18 at 18:03
  • Important to mention that here the jest config is in the `package.json`. But I could also be on a `jest.config.json` or other file. – oskrgg Jun 23 '23 at 20:12

14 Answers14

107

I think you're looking for: roots or modulePaths and moduleDirectories

You can add both relative and absolute paths.

I would make sure to include <rootDir> in the roots array, <rootDir> in the modulePaths array, and node_modules in the moduleDirectories array, unless you've got a good reason to exclude them.

"jest": {
  "roots": [
    "<rootDir>",
    "/home/some/path/"
  ],
  "modulePaths": [
    "<rootDir>",
    "/home/some/other/path"
  ],
  "moduleDirectories": [
    "node_modules"
  ],
}
Sachin Joseph
  • 18,928
  • 4
  • 42
  • 62
twils0
  • 2,431
  • 2
  • 12
  • 24
  • 1
    This helped me solved my issue in Angular. My error was `Cannot find module 'src/app/core/services/seo.service' from 'src/app/blog/blog-list/blog-list.component.ts'` and it happened after importing routerTestingModule in my spec file which was to solve an error of `NG0304: 'router-outlet' is not a known element:` In my jest.config.js ` module.exports = { preset: "jest-preset-angular", setupFilesAfterEnv: ["/setup-jest.ts"], globalSetup: "jest-preset-angular/global-setup", modulePaths: [""], // <-- adding this solved it };` – BrunoElo Feb 25 '22 at 09:53
  • 9
    `"modulePaths": ["/src/"]` was what I needed. – totymedli Mar 09 '22 at 08:04
  • 1
    "modulePaths": [ "/../" ] was it in may case :=) – c_froehlich May 13 '22 at 11:42
  • This doesn't work with Create React App. We must eject first to run this :/ – George Mylonas Aug 09 '22 at 12:07
71

Since in package.json you have:

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

Which says that each module you import will be looked into node_modules first and if not found will be looked into src directory.

Since it's looking into src directory 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 pakcage.json so that all your components could be imported as you want it.

tanguy_k
  • 11,307
  • 6
  • 54
  • 58
Hriday Modi
  • 2,001
  • 15
  • 22
  • 1
    In my case, `moduleNameMapper` was the way to go, considering we had `@` pointing to some specific root directories. – giovannipds Dec 10 '21 at 16:25
21

Adding

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

should work if you have Jest's config in your package.json file.

If you have a jest.config.js file, you should add it there, otherwise package.json will be overriden (and ignored) by this config file. So in your jest.config.js file:

module.exports = {
// ... lots of props
  moduleDirectories: ["node_modules", "src"],
// ...
}
Waclock
  • 1,686
  • 19
  • 37
7

That's because jest doesn't recognize relative imports like src/views/app

Add a rootDir and a modulePaths in package.json

"name": "my-app",
...
"jest": {
    ...
    "rootDir": "./",
    "modulePaths": [
      "<rootDir>"
    ],
    ...
  }
}
usersina
  • 1,063
  • 11
  • 28
4

Make sure you have run npm i or npm install after update the package.json. My issue was that :0

suranga upul
  • 211
  • 3
  • 6
4

In my case, I was running integration tests and all tests were in the same file with the path src/int-test.spec.ts in order to read paths I had to write:

Solution 1

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

Another way of doing this is to create jest.config.js file, The file will be discovered automatically, if it is named jest.config.js|ts|mjs|cjs|json. And put this into it:

Solution 2

const path = require('path');

module.exports = {
  moduleFileExtensions: ['js', 'json', 'ts'],
  roots: ['src'],
  testRegex: '.*\\.spec\\.ts$',
  transform: {
    '^.+\\.(t|j)s$': 'ts-jest',
  },
  collectCoverageFrom: ['**/*.(t|j)s'],
  coverageDirectory: '../coverage',
  testEnvironment: 'node',
  moduleDirectories: ['node_modules', 'src', __dirname],
};

Mathe
  • 51
  • 3
  • Additionally, if you're experiencing this issue with prefixed imports (like parcel likes to use), you can change the mapper to: `"prefix:(.*)": "$1"` and then mock the path without the prefix if needed. – Lerk Jan 25 '23 at 13:59
2

For those who are building something from scratch with Webpack and Babbel. Try the following steps:

  1. Delete the node_modules folder and install again. (This was something that solved my issue).

  2. Here is a link with the necessary documentation to set up Webpack which in some cases will not be necessary. Jest Docs Webpack

  3. Here is a link to the docs that explains how to set up Jest with React (Without using Create-React-App). Jest React Docs

4. Here is an example with a simple setup with Jest. You can set this up in package.json or the Jest configuration file.

Disclaimer: This does not answer the OP question. But most people will end up here for the keywords used for this issue.

  "jest": {
"moduleFileExtensions": ["js", "jsx"],
"moduleDirectories": ["node_modules"],
"moduleNameMapper": {
  "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
  "\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
}

},

Osv
  • 771
  • 8
  • 7
1

Adding __esModule:true fixed this issue for me.

jest.mock('module',()=>({
  __esModule: true,                    // this makes it work
  default: jest.fn()
}));

Hope this helps somebody. Although this is not very specific to the question.

Ankur Marwaha
  • 1,613
  • 2
  • 15
  • 30
1

One of the modules I wanted to use has a .cjs extension. Adding .cjs to moduleFileExtensions in jest.config.js fixed this problem for me.

My jest.config.js as example:

module.exports = {
    moduleNameMapper: {
        // see: https://github.com/kulshekhar/ts-jest/issues/414#issuecomment-517944368
        "^@/(.*)$": "<rootDir>/src/$1",
    },
    preset: "ts-jest/presets/default-esm",
    globals: {
        "ts-jest": {
            useESM: true,
        },
    },
    testEnvironment: 'jsdom',
    transform: {
        '^.+\\.vue$': 'vue3-jest',
    },
    moduleFileExtensions: ['json', 'js', 'jsx', 'ts', 'tsx', 'vue', "cjs"],
    moduleDirectories: ["node_modules"],
};

Zoidbergseasharp
  • 3,697
  • 1
  • 11
  • 20
1

This can also be caused by absolute imports present in the globalSetup file (or any files it references).

It seems like moduleNameMappers do not get applied to globalSetup files. I fixed this by just switching to relative imports for those specific files.

Mike Rippon
  • 564
  • 6
  • 11
1

This Workaround:

Using "moduleNameMapper" in your jest configuration will make test-resolve work as expected:

"jest": {
  "moduleNameMapper": {
    "#(.*)": "<rootDir>/node_modules/$1"
  }
}

https://gist.github.com/lydell/d62ce96c95c035811133a5396195da14

r31sr4r
  • 306
  • 1
  • 2
  • 12
  • 2
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 29 '22 at 03:03
1

Just add "modulePaths" to your package.json

"jest": {
    ...
    "modulePaths": [
      "<rootDir>"
    ],
    ...
  }
}
VyTor BrB
  • 81
  • 8
1

This solved it for me.

Here is my jest-e2e.json file:

{
    "moduleFileExtensions": ["js", "json", "ts"],
    "rootDir": "..",
    "globalSetup": "<rootDir>/src/integration-test/setup.ts",
    "globalTeardown": "<rootDir>/src/integration-test/teardown.ts",
    "testEnvironment": "node",
    "testRegex": ".e2e-spec.ts$",
    "transform": {
        "^.+\\.(t|j)s$": "ts-jest"
    },
    "moduleDirectories": ["<rootDir>", "node_modules"],
    "moduleNameMapper": {
        "^src/(.*)$": "<rootDir>/src/$1"
    },
    "testPathIgnorePatterns": [".*\\.e2e\\.ts$"],
    "collectCoverageFrom": ["src/**/*.ts", "!src/private/**/*.resolver.ts"],
    "coveragePathIgnorePatterns": [
        ".*\\.module\\.ts$",
        ".*\\.entity\\.ts$",
        ".*\\.dto\\.ts$",
        ".*\\.interface\\.ts$",
        ".*\\.input\\.ts$",
        ".*\\.config\\.(t|j)s$",
        ".*\\.js$",
        "/dist/",
        "/coverage/",
        "/node_modules/"
    ],
    "coverageDirectory": "./coverage",
    "transformIgnorePatterns": ["node_modules/(?!(node-fetch)/)"]
}

You can see I call "setup.ts" in there. Then I added "tsconfig-paths/register" like this in my setup.ts file:

require("tsconfig-paths/register") <---- ADDED THIS

import { integrationTestEnvSetup } from "./env-setup"
import { integrationTestSetupStuff } from "./setup-stuff"

/* Code run prior to integration test from ./jest-e2e.json */

const integrationTestSetup = async () => {
    await integrationTestEnvSetup()
    await integrationTestSetupStuff()
}

export default integrationTestSetup

Make sure you have the tsconfig-paths package installed for this as well.

The require("tsconfig-paths/register") line is used to import the tsconfig-paths package, which is a utility that allows Node.js to understand TypeScript's paths and baseUrl options directly. This is often used in conjunction with a tool like ts-node for running TypeScript code directly in Node.js without a separate compilation step.

Hope that can help anyone else! I was so happy when I realized that this worked, after hours of hair-pulling.

Dawid Dahl
  • 129
  • 1
  • 8
0

I had jest-expo installed, but not jest. Probably related that I'm prebuild-ejected from Expo. I had to run yarn add jest-expo jest to install jest, and updated jest-expo. Now my tests run.

Depending on your setup it might be, npm i jest-expo jest or expo install jest-expo jest. ... Got the idea from their docs https://docs.expo.dev/guides/testing-with-jest/

SeanMC
  • 1,960
  • 1
  • 22
  • 33