重构Angular 4和Jasmine中的测试单位

时间:2017-07-30 13:39:10

标签: angular typescript jasmine refactoring karma-jasmine

档案: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
      });
  }
}

1 个答案:

答案 0 :(得分:0)

以下是我提出的解决方案:

我创建了一个TestModule,然后我将所有导入的内容放在所有测试中。在每个spec文件中,我只导入特定于该特定测试的内容。

(样本TestModule

TestModule导出的{p> testHelper.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 {}

现在在spec文件中:

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并继续测试。

干杯