0
文件:login.component.spec.ts
在重構測試單元角4和茉莉花
- 茉莉花,噶及角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
部分)。
有沒有一種方法可以將類似的輸入放入共享模塊,然後將該模塊導入到新測試中?
(沒有一個良好的面向對象設計的做法,我知道,我只是好奇,如果這是可能的)提前
感謝。
------------- 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
});
}
}