网站搜索

typescript - 升级到 v15 后,如何包含来自 Angular 项目外部的单元测试?


自 Angular v15 起,来自 test.ts 配置文件的 require.context 函数已被移除。

我正在使用 require.context 使 Angular 项目之外的测试对 Karma 可见。现在这已被移除:

const contextGlobal = require.context('../../../folderOutsideProject/', true, /\.spec\.ts$/);
contextGlobal.keys().map(contextGlobal);

我如何可以包含来自 Angular 项目外部的测试?(v15)

我尝试在 outsideFolder 和项目文件夹之间创建一个符号链接。但它不起作用。

编辑:从我在源代码中看到的情况来看,在 webpack 编译阶段,只包括了 projectSourceRoot 路径:https://github.com/angular/angular-cli/blob/dbcea96274122db128099967fec3d1ecceafe1ab/packages/angular_devkit/build_angular/src/builders/karma/find-tests-plugin.ts#L69

答案#1

在迁移到 Angular v15 后,仍然遇到相同的问题,但没有有用的资源来解决它。因此,我查看了 angular-cli 的源代码来修复它。

原因:

在 v15 中,Angular 团队添加了 find-test-plugin,用于内部查找和加载 *.spec.ts 文件,而不是让我们使用 require.context() webpack API 外部查找和加载测试文件。

现在,这些测试是基于 angular.json 中 sourceRoot 和 include 配置的相对路径来识别的

示例项目结构:

  • 根/应用/
  • root/test/

请考虑所有 '*.spec.ts' 文件都位于测试目录中,该目录在应用程序目录之外。

angular.json中的更改:

{
  "sourceRoot": "root",
  "architect": {
      "test": {
         "builder": "@angular-devkit/build-angular:karma",
         "options": {
            "main": "root/test/test.ts",
            "polyfills": [ "zone.js","zone.js/testing" ],
            "include": ["test/**/*.spec.ts"],
        .....
        .....
}

如果不需要,您可以删除 main 配置。但如果需要,请确保删除以下两行:

const contextGlobal=require.context('../../../folderOutsideProject/', true, /.spec.ts$/); contextGlobal.keys().map(contextGlobal);

tsconfig.spec.json 的更改:

{
   "extends": "../tsconfig.json",
   "compilerOptions": {
       "types": ["jasmine"]
      },
   "include": [ "root/test/test.ts", "root/test/**/*.spec.ts"]
}