如何用Jest测试Angular 8中的scrollTop事件?

问题描述 投票:0回答:1

我已经找了两天来测试scrollTop事件的解决方案,但我没有在任何地方找到解决方案。我所有的尝试都返回了相同的错误......

TypeError: Cannot read property 'scrollTop' of undefined

header.component.ts

@HostListener('window:scroll', ['$event'])
onWindowScroll(): void {       
  if(document.scrollingElement.scrollTop > 63){
    this.headerElement.classList.add('height-63');
  }else{
    this.headerElement.classList.remove('height-63');
  }
}

header.component.spec

it('should test scrollTop', () => {
  window.scrollTo(0, 500);
  //document.scrollingElement.scrollTop = 500 --> I already tried to set the scrollTop value
  fixture.detectChanges();
  component.onWindowScroll();    
  expect(fixture.debugElement.nativeElement.querySelector('.height-63')).toBeTruthy();    
});
angular unit-testing jestjs undefined scrolltop
1个回答
0
投票

好了,朋友们,我找到了一个解决方案!我的做法是不可能继续......。所以我决定改变我检查卷轴的方式,它的工作!我改变了我的方式。

我改变

if(document.scrollingElement.scrollTop > 63)

if(window.pageYOffset > 63)

结果是这样的。

header.component.ts

@HostListener('window:scroll', ['$event'])
onWindowScroll(): void {       
  if(window.pageYOffset > 63){
    this.headerElement.classList.add('height-63');
  }else{
    this.headerElement.classList.remove('height-63');
  }
}

header.component.spec

it('should test HostListener', () => {
  component.onWindowScroll();
  expect(fixture.debugElement.nativeElement.querySelector('.height-63')).not.toBeTruthy();
  window = Object.assign(window, { pageYOffset: 100 });
  component.onWindowScroll();
  expect(fixture.debugElement.nativeElement.querySelector('.height-63')).toBeTruthy();
});

谢谢!

© www.soinside.com 2019 - 2024. All rights reserved.