Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest - cannot find module with relative import from shared (Angular)

Tags:

angular

jestjs

I have problem with custom relative path in jest. Jest cannot find module after several attempts didn't find solution for this? I have problem with this config or problem can be in other config file? If needed I can post others config files ;)

Cannot find module '@ht/tools' from 'src/app/shared/components/base-grid/base-grid.component.ts'
   Require stack:
  src/app/shared/components/base-grid/base-grid.component.ts
  src/app/shared/index.ts
  src/app/pages/registries/subpages/temperatures/components/temperature-objects-grid/temperature-objects-grid.component.ts
  src/app/pages/registries/subpages/temperatures/containers/temperatures/temperatures.component.ts
  src/app/pages/registries/subpages/temperatures/containers/temperatures/temperature.component.spec.ts

Here is my jest.config.js

module.exports = {
    preset: 'jest-preset-angular',
    globals: {
        'ts-jest': {
          tsConfig: 'src/tsconfig.spec.json',
        }
    },
    transform: {
        '^.+\\.(ts|js|html)$': 'ts-jest'
    },
    moduleNameMapper: {
        "@ht/$": "<rootDir>/src/app/shared/$1",
        '^src/(.*)$': '<rootDir>/src/$1',
        '^app/(.*)$': '<rootDir>/src/app/$1',
        '^assets/(.*)$': '<rootDir>/src/assets/$1',
        '^environments/(.*)$': '<rootDir>/src/environments/$1',
    },
    moduleFileExtensions: ['ts', 'html', 'js', 'json'],
    modulePathIgnorePatterns: ["<rootDir>/src/environments"],
    setupFilesAfterEnv: [
        '<rootDir>/src/jest.setup.ts'
    ]
};
like image 744
Wiktor Dębski Avatar asked Dec 06 '25 08:12

Wiktor Dębski


1 Answers

"@ht/$": "<rootDir>/src/app/shared/$1" mapping matches only ...@ht/ module instead of @ht/... and uses nonexistent matching group.

It should be written exactly the same way as other mappings, considering that scoped packages are directories in src/app/shared/:

'^@ht/(.*)$': '<rootDir>/src/app/shared/$1',
'^src/(.*)$': '<rootDir>/src/$1',
...
like image 139
Estus Flask Avatar answered Dec 07 '25 23:12

Estus Flask



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!