我目前使用Angular 2和Jasmine,並有一個簡單的輸入字段。我正在嘗試編寫一個單元測試,並使用Angular.io站點的這個example。鑑於它更具信息性,您可以看到plnkr。尋找app-> dashboard-> dasboard-hero.component.ts。角2 /茉莉測試輸入字段綁定
該示例使用select,我正在使用輸入並且無法獲取eventEmitter來觸發。
我的組件:
export class MyInputComponent implements OnInit {
private _myBind: string;
@Output() myBindChange = new EventEmitter();
@Input()
set myBind(bindField: string) {
this.myBindChange.emit(bindField);
this._myBind = bindField;
}
get myBind(): string {
return this._myBind;
}
的HTML:
<p><input type="text" [(ngModel)]="myBind"></p>
包括演示HTML頁面上時,這一切正常。
測試用例:
describe('Testing the Bind',() => {
let fix: ComponentFixture<MyInputComponent>;
let ele: DebugElement;
let comp: MyInputComponent;
beforeEach(() => {
fix = TestBed.createComponent(MyInputComponent);
comp = fix.componentInstance;
ele = fix.debugElement.query(By.css('input'));
comp.myBind = 'Nikki';
});
it('should emit when input added',() => {
let boundString: string;
boundString = 'zzz'; //Dummy value so bound is not null.
comp.myBindChange.subscribe((str: string)
=> boundString = str); //Listen for the event.
ele.triggerEventHandler('keypress', null); //Is the event triggered?
expect(boundString).toBe('Nikki'); //fails, it's still zzz.
}); });
我做錯了什麼,或者我可以觸發事件錯誤。
事件是否錯誤?
我的測試有什麼問題嗎?
順便說一句,我會投票的好答案。
這沒有奏效,我找到了一個非常簡單的解決方案。它有助於打印它以提出問題。 –