5

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

splash
  • 13,037
  • 1
  • 44
  • 67
artronics
  • 1,399
  • 2
  • 19
  • 28

1 Answers1

12

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()
Community
  • 1
  • 1
artronics
  • 1,399
  • 2
  • 19
  • 28