Angular 角度单元测试-无功形式值未更新

Angular 角度单元测试-无功形式值未更新,angular,unit-testing,karma-jasmine,angular-reactive-forms,Angular,Unit Testing,Karma Jasmine,Angular Reactive Forms,我不熟悉角度单元测试。 测试场景:html中的表单视图值等于组件表单值。 电子邮件值由共享值检索,并在组件注册表单中使用。我可以使用反应式表单从组件中检索电子邮件值,但是当尝试通过本机元素访问时,它会给出空值。 下面是component.ts ngOnit(public serviceEmail) { this.assignEmailAvailable(); this.createRegistration(); } assignEmailAvailable() { i

我不熟悉角度单元测试。 测试场景: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中,我将调用此函数并检查两个值是否相同。 组件规范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);
  }));

我花了两个小时试图解决这个问题。根据我的经验,beforeach()函数中有一些问题需要解决。首先,您需要将ReactiveFormsModule导入到您的测试床中,以便更改检测能够正确地执行所有操作。其次,需要在beforeach()调用中手动运行ngOnInit()和fixture.detectChanges()来设置表单。请参见下面的beforeach()函数。我还包括了其他有此问题的人可能会觉得相关的代码的其余部分

组件模板:


    <form [formGroup]='emailForm' (ngSubmit)='handleSubmit()'>
      <div class='form-group'>
        <label for='email'>Email address</label>
        <input type='email' class='form-control' id='email' placeholder='Enter email'
          formControlName='email'>

规范TS中的beforeach()调用都是:

      beforeEach(
        async(() => {
    
          apiServiceSpy = jasmine.createSpyObj('ApiService', ['sendResetPasswordEmail']);
          routerSpy = jasmine.createSpyObj('Router', ['navigateByUrl']);
    
          TestBed.configureTestingModule({
            declarations: [ SendPasswordResetEmailComponent ],
    
            // Need to import this if we're messing with Reactive Form inputs!!
            imports: [ReactiveFormsModule],
    
            providers: [
              {provide: ApiService, useValue: apiServiceSpy},
              {provide: Router, useValue: routerSpy},
              {provide: FormBuilder},
            ]
          })
          .compileComponents();
        })
      );
    
      beforeEach(() => {
        fixture = TestBed.createComponent(SendPasswordResetEmailComponent);
        component = fixture.componentInstance;
    
        // ngOnInit() doesn't get called automatically, so we have to do it ourselves
        component.ngOnInit();
    
        // Telling the fixture to detect changes is really important to correctly bind data
        // Do this after calling ngOnInit() so changes propagate to the template 
        fixture.detectChanges();
      });
样本测试规格:

      it('should have an error for no username', () => {
        const componentElement: HTMLElement = fixture.nativeElement;
        const emailInput: HTMLInputElement = componentElement.querySelector('input');
        emailInput.value = '@gmail.com';
        emailInput.dispatchEvent(new Event('input'));
        fixture.detectChanges();
        expect(component.email.errors.email).toBeTruthy('@gmail.com valid');
      });
    
      it('should have no error if the email is valid', () => {
        const componentElement: HTMLElement = fixture.nativeElement;
        const emailInput: HTMLInputElement = componentElement.querySelector('input');
        emailInput.value = 'joe@test.go';
        emailInput.dispatchEvent(new Event('input'));
        fixture.detectChanges();
        expect(component.email.errors).toBeFalsy('joe@test.go invalid');
      });

在表单控件初始化中,是否应该使用
this.email
来代替,例如
新表单控件(this.email)
?嘿,我纠正了一个打字错误。导入表单模块和反应表单模块解决了我的问题
      it('should have an error for no username', () => {
        const componentElement: HTMLElement = fixture.nativeElement;
        const emailInput: HTMLInputElement = componentElement.querySelector('input');
        emailInput.value = '@gmail.com';
        emailInput.dispatchEvent(new Event('input'));
        fixture.detectChanges();
        expect(component.email.errors.email).toBeTruthy('@gmail.com valid');
      });
    
      it('should have no error if the email is valid', () => {
        const componentElement: HTMLElement = fixture.nativeElement;
        const emailInput: HTMLInputElement = componentElement.querySelector('input');
        emailInput.value = 'joe@test.go';
        emailInput.dispatchEvent(new Event('input'));
        fixture.detectChanges();
        expect(component.email.errors).toBeFalsy('joe@test.go invalid');
      });