angular - Angular 7:ngModel 数据绑定不会在单元测试中更新组件属性
问题描述
我有一个 Angular 7 组件,searchTerm
它的模板中有一个属性和一个输入元素。属性的值通过以下方式绑定到输入元素的值[(ngModel)]="searchTerm"
:
@Component({
selector: 'app-search',
template: `
<form class="search-form">
<mat-form-field class="search-form-field">
<input matInput
type="text"
id="search-input"
[(ngModel)]="searchTerm"
name="search-input">
</mat-form-field>
</form>
`,
styleUrls: ['./search.component.scss']
})
export class SearchComponent {
searchTerm: string;
}
在我的单元测试中,我尝试测试属性是否更改为输入元素的值:
it('should update searchTerm according to the input-value', async (() => {
fixture = TestBed.createComponent(SearchComponent);
component = fixture.componentInstance;
fixture.detectChanges();
const input = fixture.debugElement
.query(By.css('#search-input')).nativeElement;
input.value = 'test-value';
input.dispatchEvent(new Event('input'));
fixture.detectChanges();
fixture.whenStable().then(() =>
expect(component.searchTerm).toEqual('test-value')
);
}));
但是,我得到的只是以下错误消息:
预期未定义等于“测试值”。
有趣的是,当我在浏览器中手动尝试时,绑定完全有效。另外,我已经尝试在我的测试函数中使用fakeAsync
而不是,async
但它没有任何区别。
我究竟做错了什么?
解决方案
推荐阅读
- jquery - 查询 mySQL 并不总是调用最新数据
- angular - 使用 ngrx 处理组件错误
- r - 匹配来来去去的位置数据
- machine-learning - 在我的情况下,我可以说随机森林比线性回归更适合吗?
- javascript - TypeScript,具有条件属性的泛型类型
- android - android 的 DCMTK 库编译
- jmeter - JMeter HTTP 测试脚本记录器随机停止记录
- c# - 没有插件的 MvvmCross iOS 汉堡菜单 iOS Native
- postgresql - Postgresql 查询的奇怪行为
- android - Google Play 商店订阅历史