简体   繁体   中英

Test IntersectionObserver in an Angular component

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM