Jasmine 测试锚元素点击而不打开选项卡

问题描述 投票:0回答:1

在我的 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 秒左右重复生成新选项卡,耗尽我的系统资源并阻止任何测试实际运行(或至少完成)。

我已经尝试了这些两个线程中的建议,但没有成功,我的谷歌-fu让我失望了。

html angular unit-testing jasmine anchor
1个回答
0
投票

尝试删除

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();
}));
© www.soinside.com 2019 - 2024. All rights reserved.