How to setup tsconfig paths in jest.config.js. Angular 8. jest-preset-angular

3.3k views Asked by At

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"
1

There are 1 answers

0
wtho On

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'
}