Angular 角度6:TypeError:无法读取属性';滚动到视图';空的
我试图在angular 6中测试scrollIntoView(),但出现以下错误-->Angular 角度6:TypeError:无法读取属性';滚动到视图';空的,angular,typescript,jasmine,karma-jasmine,Angular,Typescript,Jasmine,Karma Jasmine,我试图在angular 6中测试scrollIntoView(),但出现以下错误-->TypeError:无法读取null的属性“scrollIntoView” 规格: ts: 尝试: 规格: 角类 ngOnInit() { window.document.getElementById('info-banner').scrollIntoView(); } document.getElementById('info-banner').ScrollingToView()应该进入ngAfterV
TypeError:无法读取null的属性“scrollIntoView”
规格:
ts:
尝试:
规格:
角类
ngOnInit() {
window.document.getElementById('info-banner').scrollIntoView();
}
document.getElementById('info-banner').ScrollingToView()代码>应该进入ngAfterViewInit()
lifecyclehook
基本上,任何DOM引用都应该进入该钩子。执行ngOnInit()
时,DOM还不存在,因此会出现错误。尝试使用此选项
// Get the reference of the variable
@ViewChild("myDiv") divView: ElementRef;
this.divView.nativeElement.scrollIntoView();
Info
查看此链接
要访问外部元素,请选中此项
您是否也在测试中的文档中添加了“窗口”?文档不在angular的范围内,您必须在它前面加上window才能使用它。更新的问题仍然相同,TypeError:无法读取Null的属性“scrollIntoView”。我不太熟悉angular测试套件,但我建议您首先检查测试中是否存在window对象,也许这个套件并没有完全模仿真正的浏览器。。同时在浏览器中测试相同的代码,看看是否有效。仍然不走运:(@Ramana我的问题是,你的组件的html中是否有info横幅
?angular建议使用ViewChild
,而不是原生js函数。我的评论html中没有info横幅。你能帮我提供任何参考/示例如何使用ViewChild测试此场景吗??@Ramana组件的html中没有该元素,为什么需要引用它?对于ViewChild
,您可以阅读以下内容:一个简单的示例:在组件的html中:
;在ts中:@ViewChild('infoBanner')infoBanner:ElementRef;
和ngAfterViewInit()
您有这个.infoBanner.nativeElement.scrollIntoView();
您可以添加组件html.Info banner出现在这个component@HitechHitesh我的组件的html中没有信息横幅,我指的是使用document.getElementById(信息横幅)的不同组件…这就是它不工作的原因。是否有可能测试这个特定的场景???@hitechhitesh代码在运行时工作吗
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();
}
// Get the reference of the variable
@ViewChild("myDiv") divView: ElementRef;
this.divView.nativeElement.scrollIntoView();
<div id="info-banner" #myDiv >Info </div>