In my Angular 17 application, I have some anchor element that has both an href for navigation and a click handler. I'm not worried about testing the href, but I'm trying write a simple "should call function" test for the click handler.
In short,
<a
href="some url"
target="_blank"
(click)="handleClick()"
id="anchor-to-test"
>
Click me! :)
</a>
and the associated test:
it('should call click handler when link is clicked', fakeAsync(() => {
const onClickSpy = spyOn(component, 'handleClick');
fixture.detectChanges();
const link = fixture.debugElement.query(By.css('#anchor-to-test'));
link.click();
tick();
expect(onClickSpy).toHaveBeenCalled();
}));
When I run the test, the karma/jasmine window ends up repeatedly spawning new tabs every 5 seconds or so, chewing up my system resources and preventing any tests from actually running (or at least completing).
I have tried the suggestions in these two threads to no avail, and my google-fu is failing me.
Try removing the href
attrbute then performing the click!
it('should call click handler when link is clicked', fakeAsync(() => {
const onClickSpy = spyOn(component, 'handleClick');
fixture.detectChanges();
const link = fixture.debugElement.query(By.css('#anchor-to-test'));
link.removeAttribute("href"); // <- changed here!
fixture.detectChanges(); // <- can work without this line, if not remove it!
link.click();
fixture.detectChanges(); // <- can work without this line, if not remove it!
tick();
expect(onClickSpy).toHaveBeenCalled();
}));