如何测试Angular 2双向绑定输入值

时间:2016-09-26 14:25:07

标签: angular typescript testing 2-way-object-databinding

我正在尝试为我的组件编写测试,以测试角度双向绑定是否有效。

一方面,我有一个看起来像那样的测试(它通过了):

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值未设置。任何想法如何解决这个问题?

1 个答案:

答案 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');
}));