1

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();
});
2
  • Do you want to unit-test the behavior of scrollToSecondPage only, or do you want to do an integration test that clicks the button and checks for the appropriate behavior? Commented May 8, 2020 at 6:35
  • @PhilippMeissner, just for scrollToSecondPage behaviour Commented May 8, 2020 at 6:43

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice one. Thanks @philipp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.