Jest test with TypeScript does not recognize import alias
Asked Answered
H

3

8

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

Helvellyn answered 2/7, 2020 at 8:18 Comment(0)
H
7

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

"moduleNameMapper": {
  "^@/(.*)$": "<rootDir>/src/$1"
},
Helvellyn answered 3/7, 2020 at 7:31 Comment(0)
E
3

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>/' } */),
}
Enloe answered 30/6, 2021 at 7:53 Comment(0)
C
0

In my case, I was only able to make it work after I've manually specified each directory path in tsconfig.json. For example:

    "paths": {
      "@*": [
        "./src/*",
      ],
      "@components/*": ["src/components/*"],
      "@state/*": ["src/state/*"],
      "@test-utils/*": ["src/test-utils/*"]
    },
Cuneate answered 26/7, 2024 at 16:27 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.