【问题标题】:Angular 6: TypeError: Cannot read property 'scrollIntoView' of nullAngular 6:TypeError:无法读取 null 的属性“scrollIntoView”
【发布时间】:2020-02-20 06:59:28
【问题描述】:

我正在尝试在 Angular 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();

}

【问题讨论】:

  • 能否添加组件html。此组件中存在信息横幅
  • @HitechHitesh 我的组件的 html 中没有 info-banner,我指的是来自不同组件的 document.getElementById(info-banner)....
  • 这就是它不起作用的原因
  • 是否可以测试这个特定场景?? @HitechHitesh
  • 代码在运行中是否有效

标签: angular typescript jasmine karma-jasmine


【解决方案1】:

试试:

规格:

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

【讨论】:

  • 您是否还包括“窗口”。到测试中的文件?文档不在 Angular 的范围内,你必须在它前面加上 window 才能使用它。
  • 更新还是同样的问题,TypeError: Cannot read property 'scrollIntoView' of null
  • 我对角度测试套件不是很熟悉,但是我建议您先检查测试中是否存在窗口对象,也许套件并没有完全模仿真实的浏览器..另外测试浏览器中的相同代码,看看它是否可以工作..
【解决方案2】:

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

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

【讨论】:

  • 还是没有运气:(
  • @Ramana 我的问题是你的组件的html中有info-banner吗? angular 推荐的是使用ViewChild 而不是原生js函数。
  • 我的评论 html 中没有 info-banner。你能帮我提供任何参考/示例如何使用 ViewChild 来测试这个场景吗??
  • @Ramana 如果组件的 html 中没有该元素,为什么需要引用它?对于ViewChild,您可以阅读以下内容:angular.io/guide/…
  • 一个简单的例子:在你的组件的 html 中:<div #infoBanner></div>;在您的 ts 中:@ViewChild('infoBanner') infoBanner: ElementRef; 并在 ngAfterViewInit() 中您有 this.infoBanner.nativeElement.scrollIntoView();
【解决方案3】:

尝试使用它。

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

   this.divView.nativeElement.scrollIntoView();
<div id="info-banner" #myDiv >Info </div>

查看此链接

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

要访问外部元素,请检查此

Access DOM element outside of Angular root component

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 2019-01-26
    • 2021-11-24
    相关资源
    最近更新 更多