简体   繁体   中英

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

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM