0

I am getting below error while running jasmine unit test in angular

Error:

TypeError: Cannot read property 'scroll' of null at at BoxComponent.ngAfterViewInit (http://localhost:9876/_karma_webpack_/src/app/components/box/box.component.ts:289:14)

// component 

ngAfterViewInit() {
    document.querySelector('.form-div .form-box').scroll(0, 0);
  }
  
//unit test

it('should call ngAfterViewInit', () => {
    component.ngAfterViewInit();
    spyOn(document.querySelector('.form-div .form-box'), 'scroll').withArgs(0, 0).and.callThrough();
    expect(document.querySelector('.form-div .form-box').scroll).toHaveBeenCalledWith(0, 0);
    expect(component.ngAfterViewInit).toBeTruthy();
  });
  
  
// Error

TypeError: Cannot read property 'scroll' of null
    at <Jasmine>
    at BoxComponent.ngAfterViewInit (http://localhost:9876/_karma_webpack_/src/app/components/box/box.component.ts:289:14)

2 Answers 2

0

You are supposed to use $document instead of document then you can mock it in your tests. you can refer : Angular js unit test mock document

Sign up to request clarification or add additional context in comments.

1 Comment

I am working on Angular 9. $document i guess is used in angularjs. please correct me if i am wrong
0

I tried below code and it worked

el: ElementRef

 ngAfterViewInit() {
    if (this.el && this.el.nativeElement && this.el.nativeElement.parentElement) {
      this.el.nativeElement.parentElement.scrollTop = 0;
    }
  }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.