【问题标题】:How to reduce boiler and repeatitive code when writing test cases编写测试用例时如何减少锅炉和重复代码
【发布时间】:2020-08-09 22:07:56
【问题描述】:

我在我的app-component.spec.ts 的每个describe 部分中编写了很多锅炉和重复代码。有没有办法减少它?另一个问题是,每当我写一个新的component 时,我必须在每个describe 中显式地添加对新component 的引用。例如。

    describe('AppComponent Test suite', () => {

      let component: AppComponent;
      let fixture: ComponentFixture<AppComponent>;

      beforeEach((() => {
        TestBed.configureTestingModule({
          declarations: [
            AppComponent,
    ... //29 components need to be referrred her
          ],
          imports: [
            AppRoutingModule,
            QuillModule,
            BrowserModule,
            HttpClientModule,
            MatProgressBarModule,
            BrowserAnimationsModule,

           HttpClientXsrfModule.withOptions({cookieName: 'CJCsrfCookie', headerName: 'CJCsrfHeader'}),
            ReactiveFormsModule
          ],
          providers: [{provide: APP_BASE_HREF, useValue: '/'},
    ...//14 services need to be added here
        }).compileComponents();
      }));

      beforeEach(() => {
        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });

      fit('should create the app', (async() => {

        expect(component).toBeTruthy();
      }));
...
});

如果我写另一个describe,我将不得不再次写所有importsdeclarations。我可以避免这种情况吗?

【问题讨论】:

    标签: angular6 angular-test


    【解决方案1】:

    除非我弄错了,否则似乎很容易做到!

    我只是导入AppModule。对于任何providers,我想提供一个替代的,我只是明确提及。

    例如。

    beforeEach(async(() => {
        TestBed.configureTestingModule({
          imports: [AppModule],
          providers: [
            {provide: UserManagementService, useClass: MockUserManagementService}, //mock user management service
            ],
        })
        .compileComponents();
      }));
    

    以上替换

    beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [//23 components. These in new implementation come from AppModule
          ],
          imports: [AppModule],
          providers: [//14 services. They also some now from AppModule,
            {provide: UserManagementService, useClass: MockUserManagementService}, //mock user management service
            {provide: APP_BASE_HREF, useValue: '/'}],
        })
        .compileComponents();
      }));
    

    【讨论】:

      猜你喜欢
      • 2021-07-03
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-10
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      相关资源
      最近更新 更多