【问题标题】:How to test Angular 2 two way binding input value如何测试Angular 2双向绑定输入值
【发布时间】:2016-09-26 14:25:06
【问题描述】:

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

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

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"\>

另一方面,我想编写一个测试,首先设置输入元素的值并检查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 值。任何想法如何解决这个问题?

【问题讨论】:

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


    【解决方案1】:

    事实证明,在更新输入字段的值之前需要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 还没有被角度设置。

    将测试更改为以下即可解决问题,并且不再需要魔法 - 哇!

    it('should bind displayed value to the SearchComponent property', fakeAsync(() => {
        searchComponent.searchBoxValue = 'abc';
    
        searchCompFixture.detectChanges();
        tick();
        searchCompFixture.detectChanges();
    
    
        expect(inputEl.nativeElement.value).toBe('abc');
    }));
    

    【讨论】:

      猜你喜欢
      • 2016-08-16
      • 2017-08-28
      • 2017-04-29
      • 1970-01-01
      • 2017-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-11
      相关资源
      最近更新 更多