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. 解决方案 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 这篇关于角茉莉花形式控制单元测试值更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-16 01:44