How do I mock the click event of a function in Angular 2? For my Home Component I have:
Home Component
import { Component } from \'@
You need to get the button then click it
de.nativeElement.querySelector('.theButtonClass').click();
Then check that the stub's navigate
method is called with the correct argument
expect(mockRouter.navigate).toHaveBeenCalledWith(['/about']);
You may or may not need to use async
. If it doesn't work, you might need to use async
and wait for the asynchronous click event to stabilize
import { async } from '@angular/core/async';
it('..', async(() => {
...click();
fixture.whenStable().then(() => {
expect(mockRouter.navigate).toHaveBeenCalledWith(['/about']);
})
})
First, I recommend you writing your test in Typescript, it keeps cohesion between your components and your tests.
Here are the basic steps in your spec file:
Get the element (I recommend using an Id tag if possible)
const element = fixture.debugElement.query(By.css("#your-element"));
Trigger the event. NOTE: there must be a (click)
event on the element
element.triggerEventHandler("click", null);
Then detect the changes from the event
fixture.detectChanges();
In your HTML template, you would need to have click events pointed at the functions you wish to test (click)="redirectToUpload()"