【问题标题】:Refactoring Test Units in Angular 4 and Jasmine在 Angular 4 和 Jasmine 中重构测试单元
【发布时间】:2017-09-06 19:03:06
【问题描述】:

文件:login.component.spec.ts

  • Jasmine、Karma 和 Angular 4

代码:

// To set up
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { MaterialModule } from '@angular/material';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

// To support the view
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { PageLoginComponent } from './login.component';

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

  // To Assign
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        PageLoginComponent,
       ],
      imports: [
        RouterTestingModule,
        BrowserAnimationsModule,
        MaterialModule,
        FormsModule,
        ReactiveFormsModule,
      ]
    })
    .compileComponents();
  }));

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

  // To Tear down
  it('should be created', () => {
    expect(component).toBeDefined();
  });

  it('should return true', () => {
    component.login();
    console.log(component.form.errors);
    expect(component.form.errors.invalidLogin).toBe(true);
  });

});

要运行此测试,我需要执行所有这些导入操作。

在认证文件夹下,我有,登录组件,锁屏,确认,忘记密码。

我需要为每个组件编写测试。他们使用几乎相同的导入(至少 // set up 部分)。

有没有一种方法可以将类似的导入放入共享模块中,然后将该模块导入新的测试中?

(不是一个好的OO设计实践,我知道,我只是好奇这是否可能)

提前致谢。

------------- login.component.ts - 以备不时之需

import { UsernameValidators } from './username.validator';
import { Component } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormControl, FormGroup, Validators, FormBuilder } from '@angular/forms';

@Component({
  selector: 'my-page-login',
  styles: [],
  templateUrl: './login.component.html'
})

export class PageLoginComponent {
  form = new FormGroup({
    username: new FormControl('', [
      Validators.required
    ]),
    password: new FormControl('', Validators.required)
  });

  // Defining property - For the ease of access
  get username() {
    return this.form.get('username');
  }

  get password() {
    return this.form.get('password');
  }

  login() {
      this.form.setErrors({
        invalidLogin: true
      });
  }
}

【问题讨论】:

    标签: angular typescript jasmine refactoring karma-jasmine


    【解决方案1】:

    这是我想出的解决方案:

    我做了一个TestModule 然后我把所有的导入都放在了所有的测试中。在每个规范文件中,我只导入对该特定测试非常具体的内容。

    (样本TestModule

    TestModuletestHelper.module.ts 导出,该文件夹位于名为 testHelpers 的文件夹中

    import { RouterTestingModule } from '@angular/router/testing';
    import { ControlMessagesComponent } from './../shared/control-messages.component';
    import { DataStub } from './data.stub';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    import { BrowserModule } from '@angular/platform-browser';
    import { ApiService } from '../service/api.service';
    import { MaterialModule, MdNativeDateModule } from '@angular/material';
    import { DeliveryBoyService } from './../service/delivery-boy.service';
    import { CommonModule } from '@angular/common';
    import { FormsModule, ReactiveFormsModule, FormBuilder, NgForm } from '@angular/forms';
    import { StorageService } from './../service/storage.service';
    import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';
    
    @NgModule({
        imports: [
            BrowserModule,
            MaterialModule,
            MdNativeDateModule,
            FormsModule,
            ReactiveFormsModule,
            BrowserAnimationsModule,
            CommonModule,
            RouterTestingModule,
        ],
        declarations: [
            ControlMessagesComponent,
        ],
        providers: [
            NgForm,
            StorageService,
            { provide: ApiService, useClass: DataStub },
            FormBuilder,
        ],
        schemas: [ NO_ERRORS_SCHEMA ],
        exports: [
            CommonModule,
            ReactiveFormsModule,
            FormsModule,
            ControlMessagesComponent,
            MaterialModule,
            MdNativeDateModule,
            RouterTestingModule,
        ]
    })
    export class TestModule {}
    

    现在在一个规范文件中:

    import { TestModule } from './../../test-helpers/testHelper.module';
    import { CountdownPipe } from './../../pipes/count-down.pipe';
    import { ARegistrationService } from './../a-registration.service';
    import { ANewFormComponent } from './a-new-form.component';
    import { async, ComponentFixture, TestBed, fakeAsync } from '@angular/core/testing';
    
    describe('ANewFormComponent', () => {
      let component: ANewFormComponent;
      let fixture: ComponentFixture<ANewFormComponent>;
    
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [ ANewFormComponent, CountdownPipe ],
          imports: [
            TestModule
          ],
          providers: [
            ARegistrationService,
          ]
        })
        .compileComponents();
      }));
    
      beforeEach(() => {
        fixture = TestBed.createComponent(ANewFormComponent);
        component = fixture.componentInstance;
      });
    
    
      fit('should be created', () => {
        fixture.detectChanges();
        expect(component).toBeTruthy();
      });
    
    });
    

    就是这样。我认为这是一个非常好的重构。您可以设置 TestBed 并继续测试。

    干杯

    【讨论】:

      猜你喜欢
      • 2017-11-18
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多