1

I have a scroll-animation component which i can add to some other components in order to display a scroll animation. The scroll animation will be shown when the parent component has scroll-bar.

export class ScrollIndicatorComponent implements OnInit, OnDestroy, AfterViewInit {

constructor(private elementRef: ElementRef) {
}

...

componentHasScrollbar(): boolean {
    const parentElement = this.elementRef.nativeElement.parentElement;
    return parentElement.offsetHeight < parentElement.scrollHeight;
}

How can i mock the this.elementRef.nativeElement.parentElement and its offsetHeight and scrollHeight values, so the method componentHasScrollbar() will return true in my unit test?

Emil Kaminski
  • 1,886
  • 2
  • 16
  • 26

1 Answers1

2

I would create a function which returns this.elementRef.nativeElement.parentElement, and then in the unit test you can spy on that function and mock the result

private getParentElement(): HTMLElement {
  return this.elementRef.nativeElement.parentElement;
}

componentHasScrollbar(): boolean {
  const parentElement = this.getParentElement();
  return parentElement.offsetHeight < parentElement.scrollHeight;
}

Then in tests:

spyOn(component, 'getParentElement').and.returnValue({
   scrollHeight: 10,
   offsetHeight: 1000
})

Your tests should trust that ElementRef itself is sufficiently tested.

Some may argue that this approach is changing the code to suit the tests, but I believe this approach is encouraging cleaner code.

proxima-b
  • 324
  • 1
  • 6