Angular jest doesn't understand import path after update to 27

916 Views Asked by At

This is a weird error. So I updated jest to 27 and all stopped working

It seems to have issues with import paths. So the following

import { something } form 'src/app/components/.....';

doesn't work, but this does:

import { something } from '../../components/....';

I guess this is managed in tsconfig. This is my spec tsconfig:

{
    "extends": "./tsconfig.json",
    "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "types": [
        "jest", // 1
        "node",
        "Chrome"
    ],
    "esModuleInterop": true, // 2
    "emitDecoratorMetadata": true, // 3
    "allowSyntheticDefaultImports": true,
  },
  "files": ["src/test.ts", "src/polyfills.ts"],
  "include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}

and the main tsconfig:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "module": "es2020",
    "lib": ["es2018", "dom"],
    "types": [],
    "paths": {
      "@shared/*": ["src/shared/*"]
    },
    "skipLibCheck": true,
    "allowSyntheticDefaultImports": true,
    "noEmitHelpers": false
  },
  "files": ["src/main.ts", "src/polyfills.ts"],
  "angularCompilerOptions": {
    "strictTemplates": true,
    "fullTemplateTypeCheck": true
  }
}

Any suggestions what might cause this import issue

1

There are 1 best solutions below

1
On

Adding this option in jest.config.js should resolve this issue

moduleNameMapper: {
    '^src/(.*)$': '<rootDir>/src/$1',
    '^app/(.*)$': '<rootDir>/src/app/$1',
    '^assets/(.*)$': '<rootDir>/src/assets/$1',
    '^environments/(.*)$': '<rootDir>/src/environments/$1',
},