3

I am writing an angular2 unit test for a component. With fully using JQuery it's possible to find what event is bound to an element. However in Angular2, I am not sure it's possible or not

For example, the following code has a click event, which is a public function of a component

      <button (click)="doLogin()" [disabled]="myDisabled">Login</button>

By reading DOM element, I can make it sure all properties and data binding is correct by running a test. Only thing that I don't know is, "event binding is correct or not" because the generated html is like the following

      <button>Login</button>

I want to make it sure someone does not delete this event binding in the future by writing a test for it.

In summary, how do I know event is properly bound to DOM element?

EDIT: Is there a way to know there is click event without actually clicking it?

allenhwkim
  • 27,270
  • 18
  • 89
  • 122

1 Answers1

2

You could use the approach below (calling the click:

it('should render list', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
  return tcb.createAsync(MyList).then((componentFixture: ComponentFixture) => {
    const element = componentFixture.nativeElement;
    componentFixture.detectChanges();
    expect(element.querySelectorAll('li').length).toBe(5);
    document.getElementById('test').click();
  });
}));

See this question for more details:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Is there a way to know there is click event without clicking it? I might be wrong to ask this approach instead of triggering click event. – allenhwkim Mar 16 '16 at 16:07