【问题标题】:Angular: How to write a unit test for template variableAngular:如何为模板变量编写单元测试
【发布时间】:2020-08-23 16:01:02
【问题描述】:

单击按钮时,我正在工作页面自动滚动,并且我使用模板变量作为目标点。如何为 scrollToSecondPage 函数编写单元测试,该函数以模板 var 作为参数。

app.component.html

<section>
  <p>section 1</p>
  <button (click)="scrollToSecondPage(slide2)">Go to section 2</button>
</section>  
<section #slide2>
  <p>section 2</p>
</section>

app.component.ts

scrollToSecondPage(el: any): void {
  el.scrollIntoView({ behavior: 'smooth' });
}

app.component.spec.ts

it('should scroll down to section two', () => {
  let component = fixture.componentInstance;
  let spy = spyOn(component, 'scrollToSecondPage').and.callThrough();
  expect(spy).toHaveBeenCalled();
});

【问题讨论】:

  • 您只想对scrollToSecondPage 的行为进行单元测试,还是进行单击按钮并检查适当行为的集成测试?
  • @PhilippMeissner,仅用于scrollToSecondPage 行为

标签: angular unit-testing jasmine angular-unit-test


【解决方案1】:

如果您只想进行单元测试,这应该可以解决问题。

import createSpy = jasmine.createSpy;

it('should scroll down to section two', () => {
  let component = fixture.componentInstance;
  const scrollSpy = createSpy('scrollIntoView')
  const el = {
    scrollIntoView: scrollSpy,
  }

  component.scrollToSecondPage(el);

  expect(scrollSpy).toHaveBeenCalledWith({ behavior: 'smooth' });
});

您将创建一个可以检查调用的间谍,然后将其传递给方法并检查该间谍是否已被组件调用。

【讨论】:

  • 不错的一个。谢谢@philipp
猜你喜欢
  • 2019-11-28
  • 1970-01-01
  • 2011-10-11
  • 1970-01-01
  • 2020-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-01
相关资源
最近更新 更多