Angular 6 : TypeError: Cannot read property 'scrollIntoView' of null

标签 angular typescript jasmine karma-jasmine

我正在尝试在 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/

相关文章:

javascript - 使用 Beautify.js 在 VSCode 中导入和导出行间距

angular - 在 Angular 上运行 karma 测试时为 "Uncaught [object Object]"

javascript - 使用 i18n 翻译 Angular 2 中的数据绑定(bind)文本

typescript - 如何将对象属性名称数组映射到给定对象中名称所指向的值数组

angular - 在具有多个模块(如 JHipster)的项目中嵌套 Angular 组件

javascript - withFormik : On initial value change, 更新 props.value

typescript - 如何测试 firestore 方法

javascript - 如何在 Angular js 测试中指定 http 响应顺序?

google-maps - 带有 angular2 应用程序的 angular2-google-maps

html - 为什么我的 Ionic 3 项目上没有占位符文本