Unit testing click event in Angular

前端 未结 5 1926
闹比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:55

    to check button call event first we need to spy on method which will be called after button click so our first line will be spyOn spy methode take two arguments 1) component name 2) method to be spy i.e: 'onSubmit' remember not use '()' only name required then we need to make object of button to be clicked now we have to trigger the event handler on which we will add click event then we expect our code to call the submit method once

    it('should call onSubmit method',() => {
        spyOn(component, 'onSubmit');
        let submitButton: DebugElement = 
        fixture.debugElement.query(By.css('button[type=submit]'));
        fixture.detectChanges();
        submitButton.triggerEventHandler('click',null);
        fixture.detectChanges();
        expect(component.onSubmit).toHaveBeenCalledTimes(1);
    });
    

提交回复
热议问题