角度6:TypeError:无法读取null的属性'scrollIntoView'

时间:2019-10-24 01:18:38

标签: angular typescript jasmine karma-jasmine

我正在尝试在角度6中测试scrollIntoView()并收到此错误-> TypeError: Cannot read property 'scrollIntoView' of null

规格:

beforeEach(() => {
    fixture = TestBed.createComponent(BusinessInfoComponent);
    component = fixture.componentInstance;
    component.ngOnInit();
    spyOn(document.getElementById('info-banner'), 'scrollIntoView').and.callThrough(); 
    expect(document.getElementById('info-banner').scrollIntoView).toHaveBeenCalled();
    expect(document.getElementById('info-banner')).not.toBeDefined();
    fixture.detectChanges();
  });

ts:

ngOnInit() {
  document.getElementById('info-banner').scrollIntoView();

}

3 个答案:

答案 0 :(得分:0)

尝试:

规格:

beforeEach(() => {
    fixture = TestBed.createComponent(BusinessInfoComponent);
    component = fixture.componentInstance;
    component.ngOnInit();
    spyOn(window.document.getElementById('info-banner'), 'scrollIntoView').and.callThrough(); 
    expect(window.document.getElementById('info-banner').scrollIntoView).toHaveBeenCalled();
    expect(window.document.getElementById('info-banner')).not.toBeDefined();
    fixture.detectChanges();
  });

角类

ngOnInit() {
  window.document.getElementById('info-banner').scrollIntoView();
}

答案 1 :(得分:0)

document.getElementById('info-banner').scrollIntoView();应该进入ngAfterViewInit()生命周期挂钩。

基本上,任何DOM引用都应加入该钩子。执行ngOnInit()时,DOM还不存在,因此会出错。

答案 2 :(得分:0)

尝试使用它。

n_components
  // Get the reference of the variable 
@ViewChild("myDiv") divView: ElementRef;

   this.divView.nativeElement.scrollIntoView();

查看此链接

https://www.techiediaries.com/angular-elementref/

要访问外部元素,请检查

Access DOM element outside of Angular root component