Angular Jasmine FormControl Unit Test valueChanges

冷暖自知 提交于 2019-12-11 19:36:16

问题


I want to unit test my following method:

  this.boxValue = '';

  subscribeToFilterChanges(): void {
    this.filterBox.valueChanges
      .subscribe(
        data => {
          if (data) {
            this.boxValue = data.trim().toLowerCase();
          }
        }
      );
   }

filterBox is a FormControl:

filterBox = new FormControl('');

HTML is:

    <mat-form-field appearance="standard">
      <input matInput [formControl]="filterBox"
            id="filterBox-input">
    </mat-form-field>

I've written the unit test as:

it('verify filter changes', () => {

    let filterBoxInput = fixture.debugElement.query(By.css('#filterBox-input'));
    filterBoxInput.nativeElement.value = 'dummy';
    filterBoxInput.nativeElement.dispatchEvent(new Event('input'));
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      expect(component.boxValue).toBe('dummy1');
    });
  });

This test should fail, but still it is showing as passed, even though incorrect value is specified in .toBe()

What could be the issue?

I referred to Angular Testing: FormControl valueChanges Observable, and used it in my code as shown above, but that has not solved the problem.


回答1:


I think that the issue here is that your component is not initialized properly at the time you're manipulating your input.

You must tell Angular to perform databing by calling fixture.detectChanges(); right after creating component:

const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();

Also, as was mentioned in comments, whenStable is not needed here.

The completed test could look like:

it('verify filter changes', () => {
  const fixture = TestBed.createComponent(AppComponent);
  fixture.detectChanges();
  const component = fixture.debugElement.componentInstance;
  let filterBoxInput = fixture.debugElement.query(By.css('#filterBox-input'));
  filterBoxInput.nativeElement.value = 'dummy';
  filterBoxInput.nativeElement.dispatchEvent(new Event('input'));
  fixture.detectChanges();
  expect(component.boxValue).toBe('dummy'); // should pass
});

Ng-run Example



来源:https://stackoverflow.com/questions/58355726/angular-jasmine-formcontrol-unit-test-valuechanges

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!