I am currently using Angular 2 and Jasmine and have a simple input field. I am attempting to write a unit test and using this examplefrom the Angular.io site. Given that it is more informative, you can see the plnkr . Look for app->dashboard->dasboard-hero.component.ts.
The example uses a select, where I am using an input and unable to get the eventEmitter to fire.
My Component:
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;
}
The HTML:
<p><input type="text" [(ngModel)]="myBind"></p>
This works just fine when included on a demo HTML page.
The test case:
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.
}); });
I could be doing something wrong, or I could be triggering the wrong event.
Is the event wrong?
Is there something wrong in my test?
BTW I will up vote good answers.