SKL
SKL

Reputation: 1453

Angular: How to write a unit test for template variable

I'm working page auto scroll when click on the button and I'm using template variable as target point. How to write a unit testing for scrollToSecondPage function which has template var as param.

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

Upvotes: 0

Views: 1258

Answers (1)

Philipp Meissner
Philipp Meissner

Reputation: 5482

If you only want to unit-test, this should do the trick.

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

You will create a spy that you can check for calls, which you pass to the method and check if the spy has been called by the component afterwards.

Upvotes: 1

Related Questions