【问题标题】:How to setup tsconfig paths in jest.config.js. Angular 8. jest-preset-angular如何在 jest.config.js 中设置 tsconfig 路径。 Angular 8. 开玩笑的预设角度
【发布时间】:2020-02-23 05:32:20
【问题描述】:

我在我的 tsconfig 中设置了绝对路径,可以在服务期间按预期工作,但不能开玩笑。

示例路径如下所示:

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

【问题讨论】:

  • 您找到解决方案了吗?
  • 我必须更新导入以使用完整路径,例如从“@shared/my-shared.component”导入 { MySharedComponent };

标签: angular jestjs jest-preset-angular


【解决方案1】:

tsconfig.json 中可以有多个paths 用于@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'
}

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 2021-08-10
    • 2017-11-28
    • 2022-06-29
    • 2018-11-30
    相关资源
    最近更新 更多