【问题标题】:Angular: How to create a testing-module for a feature in an Angular app?Angular:如何为 Angular 应用程序中的功能创建测试模块?
【发布时间】:2021-12-18 15:32:59
【问题描述】:

我有一个“普通”(没什么特别的)Angular 应用程序,它具有一些共享功能。因为我想避免在组件测试中一遍又一遍地模拟这些共享功能,所以我正在考虑引入每个功能的测试模块版本。它应该看起来像这样:

SharedModule
 |
 |- drop-zone
 |   |_ (module contents skipped for brevity)
 |   |_ drop-zone.module.ts
 |   |_ drop-zone-testing.module.ts
 |
 |- other-features...
  • drop-zone.module.ts应该是一个角度模块,包括所有“prod / normal”declarationsservices等等。
  • 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'.

我已经尝试通过tsconfigexclude 中的模式*testing.module.ts 从角度构建中删除所有testing-module-文件,但无济于事:/ 我认为从构建中排除这些模块应该停止角度抱怨两个模块存在相同的声明。但它不起作用。

有没有人知道如何为 Angular 应用程序中的自定义功能创建测试模块?

【问题讨论】:

    标签: angular unit-testing testing dependency-injection module


    【解决方案1】:

    我想出了如何做到这一点 - 但这似乎是一种对我来说甚至没有太大意义的解决方法:D 但它在测试和构建中都有效:

    我应该提到,在我的解决方案中,我仍然删除了该文件,我通过tsconfig.app.json 定义了我自己的装饰器:

    {
       "exclude": ["src/**/testing/**/*"],
    }
    
    1. 创建您自己的装饰器,只需包装 NgModule 装饰器:
    // e.g. src/shared/testing/utils.ts
    export function NgTestingModule(obj: NgModule) {
      return NgModule(obj);
    }
    
    1. 在您的测试模块中使用:
    import { NgTestingModule } from '../testing/utils';
    
    @NgTestingModule({ ... })
    export class DropZoneTestingModule {}
    
    1. 在您的测试中:
    TestBed.configureTestingModule({
      imports: [DropZoneTestingModule],
    });
    

    【讨论】:

      猜你喜欢
      • 2016-12-18
      • 2015-01-12
      • 2019-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 1970-01-01
      相关资源
      最近更新 更多