2017-04-03 220 views
1

我正在嘗試測試Angular 2中的雙向綁定功能。我也通讀了其他一些答案,但仍然無法通過測試。Angular NgModel雙向綁定單元測試

當輸入字段更新時,我想運行一個測試,確保AppComponent類的searchQuery屬性與輸入字段的值相同。

如前所述,我已經閱讀了其他一些答案,因爲我已經包含了額外的代碼片斷。那麼目前可能不需要什麼呢?

組件

import { Component } from '@angular/core'; 

@Component({ 
    selector: 'app-root', 
    template: '<input type="text" name="input" [(ngModel)]="searchQuery" (change)="onChange()" id="search">', 
    styles: [''] 
}) 
export class AppComponent { 
    public searchQuery: string; 

    onChange() { 
     console.log(this.searchQuery); 
    } 

} 

單元測試

import { ComponentFixture, TestBed, async, fakeAsync, tick, ComponentFixtureAutoDetect } from '@angular/core/testing'; 
import { By } from '@angular/platform-browser'; 
import { DebugElement } from '@angular/core'; 

import { AppComponent } from './app.component'; 
import { FormsModule } from '@angular/forms'; 

describe('AppComponent',() => { 
    let comp: AppComponent; 
    let fixture: ComponentFixture<AppComponent>; 

    beforeEach(async(() => { 
    TestBed.configureTestingModule({ 
     declarations: [ AppComponent ], 
     providers: [], 
     imports: [ FormsModule ], 
     schemas: [] 
    }) 
    .compileComponents(); 
    })); 

    beforeEach(() => { 
    fixture = TestBed.createComponent(AppComponent); 
    comp = fixture.componentInstance; 
    }); 

    it('should create the app', fakeAsync(() => { 
    const de = fixture.debugElement.query(By.css("#search")); 
    const el = de.nativeElement; 

    el.value = "My string"; 

    var event = new Event('input', { 
     'bubbles': true, 
     'cancelable': true 
    }); 
    el.dispatchEvent(event); 

    tick(); 

    fixture.detectChanges(); 

    expect(comp.searchQuery).toEqual("My string"); 
    })); 
}); 

如果有更好的方法,我當然高興來解決這個問題的任何反饋。

回答

2

你有調度事件之前運行

fixture.detectChanges(); 

,以確保您的控制已初始化並註冊onChange事件

setUpControl功能

// view -> model 
dir.valueAccessor.registerOnChange(function (newValue) { 
    dir.viewToModelUpdate(newValue); 
    control.markAsDirty(); 
    control.setValue(newValue, { emitModelToViewChange: false }); 
}); 

Plunker Example

又見

+0

非常感謝,yurzui!一如既往地讚賞。並感謝Plunker的例子。 – bmd

+0

不客氣! – yurzui