I'm trying to test scrollIntoView() in angular 6 and got this error --> TypeError: Cannot read property 'scrollIntoView' of null
spec:
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();
should go into ngAfterViewInit()
lifecycle hook.
Basically any DOM referencing should go into that hook. When ngOnInit()
is executed, DOM doesn't exist yet and therefore the error.