Angular2 unit test: how to test events with tiggerEventHandler

I am trying to write a unit test event for click with angular2 rc1 . my component handles the click event using the onClick() method and changes the name field from bar to foo . see this plunker .

Now I want to fire the click event to check the value of name bar or not. look at the unit-testing.spec.ts on the plunker.

 it('should change name from foo to bar on click event', inject([], () => { return builder.createAsync(UnitTestingComponentTestController) .then((fixture: ComponentFixture<any>) => { let query = fixture.debugElement.query(By.directive(UnitTestingComponent)); expect(query).toBeTruthy(); expect(query.componentInstance).toBeTruthy(); // fixture.detectChanges(); expect(query.componentInstance.name).toBe('foo'); query.triggerEventHandler('click',{}); expect(query.componentInstance.name).toBe('bar'); // fixture.detectChanges(); }); })); 

And here is UnitTestingComponentTestController

 @Component({ selector: 'test', template: ` <app-unit-testing></app-unit-testing> `, directives: [UnitTestingComponent] }) class UnitTestingComponentTestController { } 

This test failed with this message:

 Expected 'foo' to be 'bar'. 

Here is the method signature for triggerEventHandler()

 triggerEventHandler(eventName: string, eventObj: any): void; 

My question is: how can I fire an event and test it with angular2.

One solution might be to call the onClick() method on componentInstance , but in this case we just check the inner class, not the behavior of the component

+5
source share
1 answer

After reading this article, I can now trigger the click event inside my test. This approach does not use triggerEventHandler . If your template looks something like this:

 <div class="my-class" (click)="onClick()"> <ul id="my-id"> <li></li> <li></li> </ul> </div> 

you can use fixture.nativeElement.querySelector(<your selector>).click() to fire the click event on the selected element. this approach calls the javascript click() function (see this )

You can select an element based on its id , class or path (xpath?). For instance:

 fixture.nativeElement.querySelector('.my-class').click() 

or

 fixture.nativeElement.querySelector('#my-id').click() 

or

 fixture.nativeElement.querySelector('div>ul>li').click() 
+8
source

All Articles