Unit testing click event in Angular

前端 未结 5 1901
闹比i
闹比i 2020-12-04 09:00

I\'m trying to add unit tests to my Angular 2 app. In one of my components, there is a button with a (click) handler. When the user clicks the button a function

5条回答
  •  無奈伤痛
    2020-12-04 09:54

    I'm using Angular 6. I followed Mav55's answer and it worked. However I wanted to make sure if fixture.detectChanges(); was really necessary so I removed it and it still worked. Then I removed tick(); to see if it worked and it did. Finally I removed the test from the fakeAsync() wrap, and surprise, it worked.

    So I ended up with this:

    it('should call onClick method', () => {
      const onClickMock = spyOn(component, 'onClick');
      fixture.debugElement.query(By.css('button')).triggerEventHandler('click', null);
      expect(onClickMock).toHaveBeenCalled();
    });
    

    And it worked just fine.

提交回复
热议问题