allenhwkim
allenhwkim

Reputation: 27738

angular2 test, how to test event is bound to an element

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?

Upvotes: 3

Views: 3917

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202256

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:

Upvotes: 2

Related Questions