【问题标题】:Angular Jasmine TypeError: Cannot read property 'scroll' of nullAngular Jasmine TypeError:无法读取 null 的属性“滚动”
【发布时间】:2020-05-28 11:26:51
【问题描述】:

在 Angular 中运行 jasmine 单元测试时出现以下错误

错误:

TypeError:无法读取 null 的属性“滚动” 在 在 BoxComponent.ngAfterViewInit (http://localhost:9876/_karma_webpack_/src/app/components/box/box.component.ts:289:14)

// component 

ngAfterViewInit() {
    document.querySelector('.form-div .form-box').scroll(0, 0);
  }
  
//unit test

it('should call ngAfterViewInit', () => {
    component.ngAfterViewInit();
    spyOn(document.querySelector('.form-div .form-box'), 'scroll').withArgs(0, 0).and.callThrough();
    expect(document.querySelector('.form-div .form-box').scroll).toHaveBeenCalledWith(0, 0);
    expect(component.ngAfterViewInit).toBeTruthy();
  });
  
  
// Error

TypeError: Cannot read property 'scroll' of null
    at <Jasmine>
    at BoxComponent.ngAfterViewInit (http://localhost:9876/_karma_webpack_/src/app/components/box/box.component.ts:289:14)

【问题讨论】:

    标签: angular unit-testing jasmine


    【解决方案1】:

    你应该使用 $document 而不是 document 然后你可以在你的测试中模拟它。 你可以参考:Angular js unit test mock document

    【讨论】:

    • 我正在研究 Angular 9。我猜 $document 在 angularjs 中使用。如果我错了,请纠正我
    【解决方案2】:

    我尝试了下面的代码,它成功了

    el: ElementRef
    
     ngAfterViewInit() {
        if (this.el && this.el.nativeElement && this.el.nativeElement.parentElement) {
          this.el.nativeElement.parentElement.scrollTop = 0;
        }
      }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 2020-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多