【问题标题】:How to test a scrollTop event in Angular 8 with Jest?如何使用 Jest 在 Angular 8 中测试 scrollTop 事件?
【发布时间】:2020-04-23 15:01:13
【问题描述】:

这两天我一直在寻找测试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】:

    好的朋友,我找到了解决办法! 我这样做的方式无法继续......所以我决定改变检查滚动的方式并且它起作用了!

    我变了

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

    谢谢!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      • 2020-02-25
      • 2020-03-08
      • 2020-06-14
      • 1970-01-01
      • 2019-12-02
      相关资源
      最近更新 更多