user5155835
user5155835

Reputation: 4742

Angular Jasmine FormControl Unit Test valueChanges

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

Upvotes: 2

Views: 9025

Answers (1)

yurzui
yurzui

Reputation: 214255

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

Upvotes: 0

Related Questions