问题描述
当用户滚动到页面底部时,我正在使用IntersectionObserver加载数据。
@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);
}
一切正常,但我不知道如何测试。
我认为我必须使用间谍来监视滚动或IntersectionObserver的模拟,但是我不知道如何在我的情况下使用它们。
有什么想法吗?
解决方法
模拟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();
});