我想对以下方法进行单元测试:
this.boxValue = '';
subscribeToFilterChanges(): void {
this.filterBox.valueChanges
.subscribe(
data => {
if (data) {
this.boxValue = data.trim().toLowerCase();
}
}
);
}
filterBox 是一个 FormControl:
filterBox = new FormControl('');
HTML is:
<mat-form-field appearance="standard">
<input matInput [formControl]="filterBox"
id="filterBox-input">
</mat-form-field>
我将单元测试编写为:
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');
});
});
该测试应该失败,但仍然显示为通过,即使 .toBe() 中指定了不正确的值
可能是什么问题?
我提到角度测试:FormControl valueChanges Observable https://stackoverflow.com/questions/51910630/angular-testing-formcontrol-valuechanges-observable
我认为这里的问题是你的组件在你操作你的组件时没有正确初始化input
.
您必须通过调用告诉 Angular 执行数据传输fixture.detectChanges();
创建组件后立即:
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
另外,正如评论中提到的,whenStable
这里不需要。
完成的测试可能如下所示:
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 运行示例 https://ng-run.com/edit/ybBoYER6nvdRtMn0mnq0?test=true
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)