3

I have absolute paths set up in my tsconfig that work as expected during serve however do not work for jest.

An example path looks like this:

"paths": {
    "@shared": "src/app/shared/index.ts"
}

Then in a component I can use

import { MySharedComponent, MyOtherSharedComponent } from '@shared';

I am currently trying to move to Jest for testing. In my jest.config.js I have a moduleNameMapper section:

moduleNameMapper: {
    '@shared/(.*)': 'src/app/shared/$1'
}

This results in

cannot find module @Shared

If I change my tsconfig path to this:

"paths": {
    "@shared/*": "src/app/shared/*"
}

these no longer work

import { MySharedComponent, MyOtherSharedComponent } from '@shared';

and have to be updated to this

import { MySharedComponent } from '@shared/my-shared.component';
import { MyOtherSharedComponent } from '@shared/my-other-shared.component';

the tests work fine and the project runs ok however it is a large project and I have hundreds of imports that use this format

import { MySharedComponent, MyOtherSharedComponent } from '@shared';

Is there a way to get moduleNameMapper to work with this path

"@shared": "src/app/shared/index.ts"
skyboyer
  • 22,209
  • 7
  • 57
  • 64
AngularBoy
  • 1,715
  • 2
  • 25
  • 35

1 Answers1

3

You can have several paths for @shared in tsconfig.json, one for the index.ts and others for sub-paths:

"paths": {
    "@shared": "src/app/shared/index.ts",
    "@shared/*": "src/app/shared/*"
}

For the moduleNameMapper you can also add a second one:

moduleNameMapper: {
    '@shared/(.*)': 'src/app/shared/$1',
    '@shared': 'src/app/shared/index.ts'
}
wtho
  • 500
  • 5
  • 14