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

拜拜、爱过 提交于 2019-12-23 15:39:52

问题


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?


回答1:


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:

  • How can I trigger a JavaScript event click


来源:https://stackoverflow.com/questions/36039168/angular2-test-how-to-test-event-is-bound-to-an-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!