如何在jest.config.js中设置tsconfig路径。Angular 8. jest-preset-angular

3
我在tsconfig中设置了绝对路径,这在服务期间按预期工作,但在jest中无效。一个示例路径如下:
"paths": {
    "@shared": "src/app/shared/index.ts"
}

然后在组件中,我可以使用:
import { MySharedComponent, MyOtherSharedComponent } from '@shared';

我目前正在尝试使用Jest进行测试。在我的jest.config.js文件中,我有一个moduleNameMapper部分:

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

这会导致:
cannot find module @Shared

如果我把我的tsconfig路径改成这样:
"paths": {
    "@shared/*": "src/app/shared/*"
}

这些不再起作用。
import { MySharedComponent, MyOtherSharedComponent } from '@shared';

并且必须更新为此。
import { MySharedComponent } from '@shared/my-shared.component';
import { MyOtherSharedComponent } from '@shared/my-other-shared.component';

测试工作正常,项目运行良好。但是这是一个大型项目,我有数百个使用此格式的导入。
import { MySharedComponent, MyOtherSharedComponent } from '@shared';

有没有一种方法可以让moduleNameMapper与这个路径一起使用?

"@shared": "src/app/shared/index.ts"

你找到解决办法了吗? - Abhidev
我不得不更新导入语句,使用完整的路径,例如:import { MySharedComponent } from '@shared/my-shared.component'; - AngularBoy
1个回答

3

您可以在tsconfig.json中为@shared设置多个路径,一个是index.ts的路径,其他的是子路径:

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

对于moduleNameMapper,您还可以添加第二个:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接