Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest test with TypeScript does not recognize import alias

I'm setting up the tests for my web application, which works with the Vue framework with TypeScript, using the Jest framework. Everything seems to work alright, except with the @ symbol in my imports, e.g., import { Foo } from '@/bar. Whether it's in my test files or in the source code, it doesn't understand it and returns:

Cannot find module '@/store' from 'src/tests/foo.spec.ts'

Here is my Jest configuration in package.json:

  "jest": {
    "moduleFileExtensions": [
      "js",
      "ts",
      "json",
      "vue"
    ],
    "testRegex": "(/tests/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
    "transform": {
      ".*\\.(vue)$": "vue-jest",
      "^.+\\.tsx?$": "ts-jest",
      "^.+\\.jsx?$": "babel-jest"
    },
    "testURL": "http://localhost/",
    "collectCoverage": true,
    "collectCoverageFrom": ["**/*.{ts,vue}", "!**/node_modules/**"],
    "coverageReporters": ["html", "text-summary"]
  }

Somebody has any idea how to make it work properly?

Thank you

like image 826
Bastian Nanchen Avatar asked Jun 20 '26 19:06

Bastian Nanchen


1 Answers

I eventually found a solution, I appended this to my Jest configuration in package.json:

"moduleNameMapper": {
  "^@/(.*)$": "<rootDir>/src/$1"
},
like image 59
Bastian Nanchen Avatar answered Jun 23 '26 19:06

Bastian Nanchen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!