自 Angular v15 起,
require.context
配置文件中的 test.ts
功能已被删除。
我使用 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
迁移到 Angular v15 后,最终遇到了同样的问题,但没有有用的资源来解决它。因此,通过 angular-cli 源代码来解决这个问题。
原因:
在 v15 中,Angular 团队添加了 find-test-plugin 来在内部查找并加载 *.spec.ts 文件,而不是要求我们在外部使用 require.context() webpack API 查找并加载测试文件。
现在,根据来自 sourceRoot 和 include 配置的相对路径来识别测试 angular.json
项目结构示例:
考虑所有“*.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"]
}