简体   繁体   中英

Angular - test reactive form control enable on value changes

I have to test if some controls are enabled.

ngOnChanges(): void {
this.form.get('menuVisibility').valueChanges.subscribe((visible: boolean) => {
    ['userIdVisibility', 'userOptionsVisibility', 'languageVisibility'].forEach((controlName) => {
      if (visible) {
        this.form.controls[controlName].enable();
      } else {
        this.form.controls[controlName].disable();
      }
    });
  });
}

I wrote this SPEC:

it('should dispatch action for valueChanges', fakeAsync(() => {
component.form.get('menuVisibility').setValue(true);
component.form.get('menuVisibility').updateValueAndValidity({ emitEvent: true });
component.ngOnChanges();
tick();
expect(component.form.get('userIdVisibility').enabled).toBeTruthy();
expect(component.form.get('userOptionsVisibility').enabled).toBeTruthy();
expect(component.form.get('languageVisibility').enabled).toBeTruthy();
  }));

But the test never enters in the forEach block.

I agree with @MoxxiManagarm where it is a memory leak, I would move it to the ngOnInit .

For a quick unblock, try calling ngOnChanges() first before setting the value so the observable stream is subscribed before we change the values:

it('should dispatch action for valueChanges', fakeAsync(() => {
  component.ngOnChanges();
  component.form.get('menuVisibility').setValue(true);
  component.form.get('menuVisibility').updateValueAndValidity({ emitEvent: true });

  tick();
  expect(component.form.get('userIdVisibility').enabled).toBeTruthy();
  expect(component.form.get('userOptionsVisibility').enabled).toBeTruthy();
  expect(component.form.get('languageVisibility').enabled).toBeTruthy();
   }));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM