Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 unit test: how to test events with triggerEventHandler

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

Now I want to fire a click event to test whether name value is bar or not. please see unit-testing.spec.ts file on 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 fails 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 onClick() method on componentInstance but in this case we just test internal of the class and not the component behavior

like image 390
artronics Avatar asked Jun 18 '16 22:06

artronics


1 Answers

After reading this article, now I can trigger click event inside my test. This approach doesn't use triggerEventHandler. If your template is 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 trigger click event on selected element. this approach calls javascript click() function (see this)

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

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

or

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

or

fixture.nativeElement.querySelector('div>ul>li').click()
like image 132
artronics Avatar answered Oct 13 '22 01:10

artronics