我想在多个角度单元测试中重用部分提供程序列表

时间:2019-05-02 06:27:22

标签: angular typescript unit-testing

我对Angular / Typescript很陌生。由于我正在启动一个新应用程序,因此我也将深入研究组件和服务的单元测试。我的大多数组件都使用DI进行服务。在测试这些组件时,我不仅需要提供模拟服务(例如我的UserService),还需要提供UserService使用的所有依赖项的类。我已经开始工作了,但是我在多个单元测试文件中重用了列表opf提供程序。作为一名程序员,我不喜欢这样,并且希望重用此列表的一部分(尽管说一个常量)。

下面的代码是我使用的。我的问题与提供者有关:[]。除少数服务外,每个规范都需要其中大多数功能。

describe('HeaderMenuComponent', () => {
  let component: HeaderMenuComponent;
  let fixture: ComponentFixture<HeaderMenuComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [HeaderMenuComponent],
      imports: [
        CookieModule.forRoot(),
        HttpClientModule,
        HttpModule,
        RouterTestingModule
      ],
      providers: [CookieService, CookieModule, CookieOptionsProvider, BaseService, AuthenticationService,
        { provide: XHRBackend, useClass: MockBackend },
        { provide: ConfigurationService, useClass: ConfigurationMockService },
        { provide: UserService, useClass: UserMockService },
        {
          // Here we request that configuration loading be done at app-
          // initialization time (prior to rendering)
          provide: APP_INITIALIZER,
          useFactory: (configService: ConfigurationService) =>
            () => configService.loadConfigurationData(),
          deps: [ConfigurationService],
          multi: true
        },
        { provide: 'BASE_URL', useFactory: '', deps: [] }]
    })
      .compileComponents();
  }));

我希望代码看起来像这样,其中DefaultProvidersList包含在多个测试中重复使用的提供程序以及特定于当前文件的服务1和2。

providers: [DefaultProvidersList, Service1, Service2]

1 个答案:

答案 0 :(得分:0)

我想出了一种方法来完成上述任务。不确定代码样式是否正确,但是可以完成工作。

我创建了一个名为unittest.ext.ts的文件,并在其中创建了一个类以及两个函数,即getImports()和getProviders。见下文,希望对您有所帮助。如果有人有更好的主意,请告诉我。

export const UnitTestExtensions = {
  hasClass: function (element, cls) {
    var classes = element.getAttribute('class');
    var split = classes.split(' ');
    return split.indexOf(cls) !== -1;
  },
   getProviders: function () {
     return [UtilityService, CookieService, CookieModule, CookieOptionsProvider, BaseService, HeaderService, LoadingService,
       { provide: XHRBackend, useClass: MockBackend },
       { provide: ConfigurationService, useClass: ConfigurationMockService },
       { provide: UserService, useClass: UserMockService },
       { provide: AuthenticationService, useClass: AuthenticationMockService },
       {
         // Here we request that configuration loading be done at app-
         // initialization time (prior to rendering)
         provide: APP_INITIALIZER,
         useFactory: (configService: ConfigurationService) =>
           () => configService.loadConfigurationData(),
         deps: [ConfigurationService],
         multi: true
       },
       { provide: 'BASE_URL', useFactory: '', deps: [] }];
  },

  getImports: function () {
    return [FormsModule,
      RouterTestingModule,
      CookieModule.forRoot(),
      HttpClientModule,
      HttpModule];
  }

};