typescript - 更新到 27 后,Angular jest 无法理解导入路径

标签 typescript jestjs tsconfig tsconfig-paths angular-jest

这是一个奇怪的错误。所以我将 jest 更新为 27,然后全部停止工作

导入路径似乎有问题。所以如下

import { something } form 'src/app/components/.....';

不起作用,但这可以:

import { something } from '../../components/....';

我猜这是在 tsconfig 中管理的。这是我的spec tsconfig:

{
    "extends": "./tsconfig.json",
    "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "types": [
        "jest", // 1
        "node",
        "Chrome"
    ],
    "esModuleInterop": true, // 2
    "emitDecoratorMetadata": true, // 3
    "allowSyntheticDefaultImports": true,
  },
  "files": ["src/test.ts", "src/polyfills.ts"],
  "include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}

和主要的 tsconfig:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "module": "es2020",
    "lib": ["es2018", "dom"],
    "types": [],
    "paths": {
      "@shared/*": ["src/shared/*"]
    },
    "skipLibCheck": true,
    "allowSyntheticDefaultImports": true,
    "noEmitHelpers": false
  },
  "files": ["src/main.ts", "src/polyfills.ts"],
  "angularCompilerOptions": {
    "strictTemplates": true,
    "fullTemplateTypeCheck": true
  }
}

任何可能导致此导入问题的建议

最佳答案

jest.config.js 中添加此选项应该可以解决此问题

moduleNameMapper: {
    '^src/(.*)$': '<rootDir>/src/$1',
    '^app/(.*)$': '<rootDir>/src/app/$1',
    '^assets/(.*)$': '<rootDir>/src/assets/$1',
    '^environments/(.*)$': '<rootDir>/src/environments/$1',
},

关于typescript - 更新到 27 后,Angular jest 无法理解导入路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68150401/

相关文章:

reactjs - 在模块中使用 FormattedMessage 时出错 : Error: [React Intl] Could not find required `intl` object

typescript - 如何从 ApplicationContext 获取实体的存储库

node.js - 我如何使用sequelize-typescript从单个字段引用多个模型?

typescript - 当有返回类型时,是否可以强制 typescript 编译器检查所​​有可能的分支?

javascript - 如何在单个测试的基础上更改模拟实现?

reactjs - 如何修复 axiosInstance.get ('url' 失败的 moxios 测试。then(...).finally 不是一个函数

typescript - 设置 tsconfig 忽略 "Property ' foo' does not exist on type 'bar' ."but only for a specific variable

angular - 与 ngIf 绑定(bind)

typescript - 'CustomEnum.Case' 可分配给类型 'T' 的约束,但 'T' 可以使用约束 'CustomEnum' 的不同子类型进行实例化

javascript - 我应该如何正确触发更改事件以在单元测试中触发函数?