我正在使用@ angular/cli 1.0.0-beta.30學習Angular 2和單元測試,並且有一點成功測試了表單字段有效性的一個方面,但並非全部。我在我的組件中使用了內聯模板,暫時去除了一層複雜性(單獨文件中的表單模板引入了異步性,是正確的?)。問題單元測試角度反應性表單字段
ngOnInit()
定義了一個name
屬性,其中包含「required」和「minLength」的驗證器。目前,一個空的表單字段將正確地觸發「必需的」驗證器,但不會觸發「minLength」驗證器。 name.errors
陣列在測試中根本不包含任何需要的參考,name.errors['minLength']
返回undefined
。 minLength是否需要異步處理?我無法找到符合我的問題的文檔或示例。
// signup-form.component.ts
...
export class SignupFormComponent implements OnInit {
user: FormGroup;
constructor(private fb: FormBuilder) {
}
ngOnInit() {
this.user = this.fb.group({
name: ['', [Validators.required, Validators.minLength(2)]],
account: this.fb.group({
email: ['', Validators.required, Validators.pattern("[^ @]*@[^ @]*")],
confirm: ['', Validators.required]
})
})
}
onSubmit({ value, valid }: { value: User, valid: boolean }) {
console.log(value, valid);
}
}
我測試
// signup-form.component.spec.ts
import { SignupFormComponent } from './signup-form.component';
describe('SignupFormComponent',() => {
let component: SignupFormComponent;
let fixture: ComponentFixture<SignupFormComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [SignupFormComponent],
imports: [
ReactiveFormsModule,
FormsModule
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SignupFormComponent);
component = fixture.componentInstance;
component.ngOnInit();
fixture.detectChanges();
});
it('should create',() => {
expect(component).toBeTruthy();
});
it('form invalid when empty',() => {
expect(component.user.valid).toBeFalsy();
});
it('name field validity',() => {
let name = component.user.controls['name'];
expect(name.valid).toBeFalsy();
let errors = {};
name.setValue("");
errors = name.errors || {};
expect(errors['required']).toBeTruthy(); // this works
expect(errors['minLength']).toBeTruthy(); // this fails, "undefined"
});
});