在我的 Angular 17 应用程序中,我有一些锚元素,它同时具有用于导航的 href 和 单击处理程序。我不担心测试 href,但我正在尝试为点击处理程序编写一个简单的“应该调用函数”测试。
简而言之,
<a
href="some url"
target="_blank"
(click)="handleClick()"
id="anchor-to-test"
>
Click me! :
</a>
以及相关测试:
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();
}));
当我运行测试时,karma/jasmine 窗口最终会每 5 秒左右重复生成新选项卡,耗尽我的系统资源并阻止任何测试实际运行(或至少完成)。
尝试删除
href
属性,然后执行单击!
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();
tick();
expect(onClickSpy).toHaveBeenCalled();
}));