Angular 16 - 所有测试中的全局导入

问题描述 投票:0回答:1

我正在使用 Angular 16 和 Karma/Jasmine。我希望在所有测试中默认导入一个模块,但无法找到可以配置的位置。我看到这篇文章使用了 test.ts 文件,但我的项目不包括这个。

如何包含此 test.ts 文件以便在我的所有测试中全局导入模块?

javascript angular karma-jasmine
1个回答
0
投票

好吧,我在发帖之前设法回答了自己的问题,但无论如何我还是把它放在这里。

从 Angular 15 开始,不再自动生成

test.ts
文件。但是,您仍然可以手动创建:

src/test.ts:

// This file is required by karma.conf.js and loads recursively all the .spec and framework files

import { getTestBed } from '@angular/core/testing';
import { MyModuleToImport} from 'somewhere...';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting,
} from '@angular/platform-browser-dynamic/testing';
import 'zone.js/testing';

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  [BrowserDynamicTestingModule, MyModuleToImport],
  platformBrowserDynamicTesting()
);

angular.json:(添加

"main": "src/test.ts"


...

        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          }
        }
      }
    }
  }
}

tsconfig.spec.json

/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "types": ["jasmine"]
  },
  "files": ["src/test.ts"],
  "include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}

© www.soinside.com 2019 - 2024. All rights reserved.