Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moduleNameMapper has no effect using Jest in Angular CLI

I'm trying to use Jest with angular cli. I have the following in my tsconfig:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "importHelpers": true,
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "module": "es2020",
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "noUnusedLocals": true,
    "noImplicitThis": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2015",
    "typeRoots": ["node_modules/@types"],
    "lib": ["es2017", "es2018.promise", "dom"],
    "paths": {
      "@src/*": ["src/*"],
      "@app/*": ["src/app/*"],
      "@core/*": ["src/app/@core/*"],
      "@shared/*": ["src/app/@shared/*"],
    }
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true,
    "strictTemplates": true
  }
}

And the following in my jest.config.js:

module.exports = {
  preset: 'ts-jest',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
  testPathIgnorePatterns: ['/node_modules/', '/dist/', 'src/app/*.{js}'],
  collectCoverage: true,
  coverageDirectory: 'jest-coverage',
  moduleNameMapper:{
    '^@src/(.*)$': '<rootDir>/src/$1',
    '^@app/(.*)$': '<rootDir>/src/app/$1',
    '^@core/(.*)$': '<rootDir>/src/app/@core/$1',
    '^@shared/(.*)$': '<rootDir>/src/app/@shared/$1',
  },
};

ng serve and ng build work correctly. Just ng test doesn't compile with: Cannot find module for every import statement using a path from paths.

Can anyone tell why this isn't working?

like image 859
yccteam Avatar asked May 06 '26 18:05

yccteam


1 Answers

I'm sure you've probably come right since posting this, but the following works for me - I suspect that the pattern matching may have interfered :(

I do also just use the jest-preset-angular config instead.

module.exports = {
 preset: "jest-preset-angular",
 globalSetup: "jest-preset-angular/global-setup",
 moduleNameMapper: {
   "@app/(.*)": "<rootDir>/src/app/$1",
   "@env": "<rootDir>/src/environments/environment",
   "@test/(.*)": "<rootDir>/src/test/$1",
 },
 roots: ["<rootDir>/src"],
};
like image 174
jarodsmk Avatar answered May 10 '26 01:05

jarodsmk



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!