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

edd*_*P23 3 testing 2-way-object-databinding typescript angular

我正在尝试为我的组件编写测试来测试角度双向绑定是否正常工作.

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

it('should bind displayed value to the SearchComponent property', () => {
    searchComponent.searchBoxValue = 'abc';
    searchCompFixture.detectChanges();
    expect(inputEl.nativeElement.getAttribute('ng-reflect-model')).toBe('abc');
});
Run Code Online (Sandbox Code Playgroud)

哪里

searchCompFixture = TestBed.createComponent(SearchComponent);
inputEl = searchCompFixture.debugElement.query(By.css('#search-box-input'));
Run Code Online (Sandbox Code Playgroud)

<input
    id="search-box-input"
    [(ngModel)]="searchBoxValue"\>
Run Code Online (Sandbox Code Playgroud)

另一方面,我想编写一个测试,首先设置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');
}));
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为searchComponent.searchBoxValue没有设置值.任何想法如何解决这一问题?

edd*_*P23 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');
}));
Run Code Online (Sandbox Code Playgroud)

编辑:我发现测试的另一个改进should bind displayed value to the SearchComponent property.我不喜欢它是因为我使用了奇怪的角度属性ng-reflect-model而不是正常的方式inputEl.nativeElement.value.这个问题是value没有通过角度设置.

将测试改为以下解决问题,不再需要魔法了 - 万岁!

it('should bind displayed value to the SearchComponent property', fakeAsync(() => {
    searchComponent.searchBoxValue = 'abc';

    searchCompFixture.detectChanges();
    tick();
    searchCompFixture.detectChanges();


    expect(inputEl.nativeElement.value).toBe('abc');
}));
Run Code Online (Sandbox Code Playgroud)