0

I'm using an IntersectionObserver to load data when user scroll to the bottom of the page.

@Output() onScroll = new EventEmitter();
@ViewChild('end') endOfList!: ElementRef<HTMLElement>;

observer!: IntersectionObserver;

constructor(private requests: ElementRef) { }

ngAfterViewInit() {
  this.observer = new IntersectionObserver(([entry]) => {
    entry.isIntersecting && this.onScroll.emit();
  }, this.requests.nativeElement);

  this.observer.observe(this.endOfList.nativeElement);
}

Everything works fine but I can't figure out how to test it.

I think I have to use a spy to spy on scroll or a mock of IntersectionObserver but I don't understand how to use them in my case.

Any ideas?

metodribic
  • 1,561
  • 17
  • 27
JoH
  • 514
  • 1
  • 6
  • 16

1 Answers1

1

Mock the IntersectionObserver :

beforeEach(() => {
  fixture = TestBed.createComponent(RequestsInfiniteListComponent);
  component = fixture.componentInstance;

  class IntersectionObserver {
    observe: () => void;
    unobserve: () => void;

    constructor(
      public callback: (entries: Array<IntersectionObserverEntry>) => void
    ) {
      this.observe = jasmine.createSpy('observe');
      this.unobserve = jasmine.createSpy('unobserve');
    }
  }
  /* eslint-disable  @typescript-eslint/no-explicit-any */
  (window as any).IntersectionObserver = IntersectionObserver;
  fixture.detectChanges();
});
metodribic
  • 1,561
  • 17
  • 27
JoH
  • 514
  • 1
  • 6
  • 16