在 Angular 15 项目中的 src 文件夹外部进行业力测试

Nil*_*son 4 karma-runner karma-jasmine angular-cli angular angular15

我在项目根级别的测试文件夹中的 src 文件夹之外有 karma 测试规范文件。将 Angular 从 14 更新到 15 后,karma 需要测试规范文件位于 angular.json 文件中 sourceRoot 指定的任何文件夹中。

// angular.json
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "project-name": {
      "root": "",
      "sourceRoot": "", // <<===
Run Code Online (Sandbox Code Playgroud)

有没有办法告诉 karma 查看工作空间根级别以向下进行测试,而不更改 angular.json 中的 sourceRoot 属性?

我将 sourceRoot 路径更改为“”,然后 Karma 会找到位于工作区文件夹及其下方的测试,因为我正在寻找带有 **/*.spec.ts 的测试

// tsconfig.spec.json
"include": [
    "**/*.spec.ts",
    "**/*.d.ts",
  ]
Run Code Online (Sandbox Code Playgroud)

Nil*_*son 5

所以我要回答我自己的问题。此答案还将 sourceRoot 值保留为您选择的任何值。答案是,在 angular.json 文件中,您需要在每个项目测试配置中包含相对于该项目配置的 sourceRoot 的规范文件。就像这样:

// angular.json
"test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "polyfills": ["zone.js/testing", "zone.js"],
            "tsConfig": "test/tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "include": [
              "../test/**/**.spec.ts",
              "../test/**/**.d.ts"
            ]
          }
        }
Run Code Online (Sandbox Code Playgroud)

然后,您还需要将这些相同的文件包含在与每个测试配置相关的 tsconfig.spec.json 文件中。就像这样:

// tsconfig.spec.json
{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/spec",
    "types": [
      "jasmine",
      "node"
    ]
  },
  "files": [
    "../demo/src/polyfills.ts"
  ],
  "include": [
    "**/*.spec.ts"
  ]
}
Run Code Online (Sandbox Code Playgroud)