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

时间:2020-04-23 15:01:13

标签: angular unit-testing jestjs undefined scrolltop

我一直在寻找一种解决方案来测试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();    
});

1 个答案:

答案 0 :(得分: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();
});

谢谢!

相关问题