我正在尝试在 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();
}
最佳答案
document.getElementById('info-banner').scrollIntoView();
应该进入 ngAfterViewInit()
生命周期 Hook 。
基本上任何 DOM 引用都应该进入该钩子(Hook)。当执行ngOnInit()
时,DOM还不存在,因此出现错误。
关于 Angular 6 : TypeError: Cannot read property 'scrollIntoView' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58532855/