Jest test with TypeScript does not recognize import alias

Viewed 2228

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

2 Answers

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

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

From the ts-jest docs path-mapping section:

// jest.config.js
const { pathsToModuleNameMapper } = require('ts-jest/utils')
// In the following statement, replace `./tsconfig` with the path to your `tsconfig` file
// which contains the path mapping (ie the `compilerOptions.paths` option):
const { compilerOptions } = require('./tsconfig')

module.exports = {
  // [...]
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths /*, { prefix: '<rootDir>/' } */),
}
Related