Unit testing click event in Angular

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

    Events can be tested using the async/fakeAsync functions provided by '@angular/core/testing', since any event in the browser is asynchronous and pushed to the event loop/queue.

    Below is a very basic example to test the click event using fakeAsync.

    The fakeAsync function enables a linear coding style by running the test body in a special fakeAsync test zone.

    Here I am testing a method that is invoked by the click event.

    it('should', fakeAsync( () => {
        fixture.detectChanges();
        spyOn(componentInstance, 'method name'); //method attached to the click.
        let btn = fixture.debugElement.query(By.css('button'));
        btn.triggerEventHandler('click', null);
        tick(); // simulates the passage of time until all pending asynchronous activities finish
        fixture.detectChanges();
        expect(componentInstance.methodName).toHaveBeenCalled();
    }));
    

    Below is what Angular docs have to say:

    The principle advantage of fakeAsync over async is that the test appears to be synchronous. There is no then(...) to disrupt the visible flow of control. The promise-returning fixture.whenStable is gone, replaced by tick()

    There are limitations. For example, you cannot make an XHR call from within a fakeAsync

提交回复
热议问题