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-returningfixture.whenStable
is gone, replaced bytick()
There are limitations. For example, you cannot make an XHR call from within a
fakeAsync