【发布时间】:2020-04-25 12:56:16
【问题描述】:
我是角度单元测试的新手。 测试场景:html中的表单视图值等于组件表单值。 电子邮件值由共享值检索并在组件注册表单中使用。我可以使用响应式表单从组件中检索电子邮件值,但是当尝试通过本机元素访问时,它给出了空值。 下面是component.ts
ngOnit(public serviceEmail) {
this.assignEmailAvailable();
this.createRegistration();
}
assignEmailAvailable() {
if(service.email){
this.email = serviceEmail.email;
}
}
createRegistration() {
this.registerForm = new FormGroup({
email:new FormControl({value:this.email})
})
}
在component.spec.ts中,我将调用这个函数并检查两个值是否相同。 组件.spec.ts
beforeEach(() => {
fixture = TestBed.createComponent(RegisterComponent);
component = fixture.componentInstance;
service = TestBed.get(serviceEmail);
});
it('Registration Form Creation', fakeAsync(() => {
service.email = "dsf@gmail.com";
fixture.detectChanges();
component.assignEmailAvailable();
component.createRegisterForm();
fixture.detectChanges();
fixture.whenStable().then(() => {
const email = fixture.debugElement.query(By.css('input[id="email"]')).nativeElement;
//The value is empty even after creating the form using the component function
expect(email.value).toBe(component.emailValue);
});
//THis returns me the value set
expect(component.registerForm.get('email').value).toBe(component.emailValue);
}));
【问题讨论】:
-
在表单控件初始化中,是否应该使用
this.email,例如new FormControl(this.email)? -
嘿,我纠正了一个错字。
标签: angular unit-testing karma-jasmine angular-reactive-forms