我正在尝试为我的组件编写测试,以测试角度双向绑定是否有效。
一方面,我有一个看起来像那样的测试(它通过了):
it('should bind displayed value to the SearchComponent property', () => {
searchComponent.searchBoxValue = 'abc';
searchCompFixture.detectChanges();
expect(inputEl.nativeElement.getAttribute('ng-reflect-model')).toBe('abc');
});
其中
searchCompFixture = TestBed.createComponent(SearchComponent);
inputEl = searchCompFixture.debugElement.query(By.css('#search-box-input'));
和
<input
id="search-box-input"
[(ngModel)]="searchBoxValue"\>
另一方面,我想编写一个测试,首先设置input元素的值,并检查SearchComponent
属性值是否已更改。我的尝试:
it('should bind SearchComponent property to the displayed value', fakeAsync(() => {
inputEl.nativeElement.value = 'abc';
let evt = new Event('input');
inputEl.nativeElement.dispatchEvent(evt);
tick();
searchCompFixture.detectChanges();
expect(searchComponent.searchBoxValue).toBe('abc');
}));
但这不起作用,因为searchComponent.searchBoxValue
值未设置。任何想法如何解决这个问题?
答案 0 :(得分:5)
事实证明,在更新输入字段的值之前需要detechtChanges
(idk为什么)。这是工作测试:
it('should bind SearchComponent property to the displayed value', fakeAsync(() => {
searchCompFixture.detectChanges();
inputEl.nativeElement.value = 'abc';
let event = new Event('input');
inputEl.nativeElement.dispatchEvent(event);
tick();
expect(searchCompFixture.componentInstance.searchBoxValue).toEqual('abc');
}));
修改强>:
我发现了测试should bind displayed value to the SearchComponent property
的另一项改进。我不喜欢的是我使用了奇怪的角度属性ng-reflect-model
而不是正常的inputEl.nativeElement.value
方式。这个问题是value
还没有被角度设置。
将测试更改为以下内容可以解决问题并且不再需要任何魔法 - hoorah!
it('should bind displayed value to the SearchComponent property', fakeAsync(() => {
searchComponent.searchBoxValue = 'abc';
searchCompFixture.detectChanges();
tick();
searchCompFixture.detectChanges();
expect(inputEl.nativeElement.value).toBe('abc');
}));