Angular:如何为 Angular 应用中的功能创建测试模块?
Angular: How to create a testing-module for a feature in an Angular app?
我有一个“普通”(没什么特别的)Angular 应用程序,具有一些共享功能。因为我想避免在组件测试中一遍又一遍地模拟这些共享功能,所以我正在考虑为每个功能引入一个测试模块版本。它应该看起来像这样:
SharedModule
|
|- drop-zone
| |_ (module contents skipped for brevity)
| |_ drop-zone.module.ts
| |_ drop-zone-testing.module.ts
|
|- other-features...
drop-zone.module.ts
应该是一个angular模块,包括所有“prod/normal”declarations
、services
等等。
drop-zone-testing.module.ts
还应包括“正常”declarations
但例如虚假服务。
但是当这样做时,我在 运行 ng build
:
时得到 Angular 错误
The Component 'FileDropZoneComponent' is declared by more than one NgModule.
- 'FileDropZoneComponent' is listed in the declarations of the NgModule 'FileDropTestingModule'.
- 'FileDropZoneComponent' is listed in the declarations of the NgModule 'FileDropModule'.
我已经尝试通过 tsconfig
的 exclude
中的模式 *testing.module.ts
从 angular-build 中删除所有 testing-module
-files,但是无济于事:/我认为从构建中排除这些模块应该停止 angular 抱怨两个模块存在相同的声明。但是没用。
有没有人知道如何在 Angular 应用程序中为自定义功能创建测试模块?
我想出了如何去做 - 但它似乎是一个对我来说甚至没有太多意义的解决方法 :D 但它在测试和构建中都有效:
我应该提一下,在我的解决方案中我仍然删除了文件,我在 via tsconfig.app.json
:
中定义了我自己的装饰器
{
"exclude": ["src/**/testing/**/*"],
}
- 创建您自己的装饰器,简单地包装
NgModule
装饰器:
// e.g. src/shared/testing/utils.ts
export function NgTestingModule(obj: NgModule) {
return NgModule(obj);
}
- 在您的测试模块中使用:
import { NgTestingModule } from '../testing/utils';
@NgTestingModule({ ... })
export class DropZoneTestingModule {}
- 在你的测试中:
TestBed.configureTestingModule({
imports: [DropZoneTestingModule],
});
我有一个“普通”(没什么特别的)Angular 应用程序,具有一些共享功能。因为我想避免在组件测试中一遍又一遍地模拟这些共享功能,所以我正在考虑为每个功能引入一个测试模块版本。它应该看起来像这样:
SharedModule
|
|- drop-zone
| |_ (module contents skipped for brevity)
| |_ drop-zone.module.ts
| |_ drop-zone-testing.module.ts
|
|- other-features...
drop-zone.module.ts
应该是一个angular模块,包括所有“prod/normal”declarations
、services
等等。drop-zone-testing.module.ts
还应包括“正常”declarations
但例如虚假服务。
但是当这样做时,我在 运行 ng build
:
The Component 'FileDropZoneComponent' is declared by more than one NgModule.
- 'FileDropZoneComponent' is listed in the declarations of the NgModule 'FileDropTestingModule'.
- 'FileDropZoneComponent' is listed in the declarations of the NgModule 'FileDropModule'.
我已经尝试通过 tsconfig
的 exclude
中的模式 *testing.module.ts
从 angular-build 中删除所有 testing-module
-files,但是无济于事:/我认为从构建中排除这些模块应该停止 angular 抱怨两个模块存在相同的声明。但是没用。
有没有人知道如何在 Angular 应用程序中为自定义功能创建测试模块?
我想出了如何去做 - 但它似乎是一个对我来说甚至没有太多意义的解决方法 :D 但它在测试和构建中都有效:
我应该提一下,在我的解决方案中我仍然删除了文件,我在 via tsconfig.app.json
:
{
"exclude": ["src/**/testing/**/*"],
}
- 创建您自己的装饰器,简单地包装
NgModule
装饰器:
// e.g. src/shared/testing/utils.ts
export function NgTestingModule(obj: NgModule) {
return NgModule(obj);
}
- 在您的测试模块中使用:
import { NgTestingModule } from '../testing/utils';
@NgTestingModule({ ... })
export class DropZoneTestingModule {}
- 在你的测试中:
TestBed.configureTestingModule({
imports: [DropZoneTestingModule],
});