Angular: 如何为模板变量编写单元测试

Angular: How to write a unit test for template variable

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

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();
});

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

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' });
});

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