cannot read properties of undefined reading subscribe testing jasmine angular

1.3k Views Asked by At

Hi I trying to test http request but , when I call a function in the ngOnInit it show me that message "cannot read properties of undefined" can somebody help me?

this is my test


  it('xxxx', () => {
    userServiceSpy.getUser.and.returnValue(of());
    const spygetUserTwo = spyOn(
      component,
      'getUserTwo'
    ).and.callThrough();
    component.ngOnInit();
    expect(spygetUserTwo).toHaveBeenCalled();
  });
```

The component

```
ngOnInit(): void {
    this.getUserTwo();
  }

  getUserTwo() {
    this.userService.getUser().subscribe(
      (val: any) => {
        console.log('xxx', val);
        this.user = val;
      },
      (err) => {
        console.log('err', err);
      }
    );
  }
```
1

There are 1 best solutions below

8
AliF50 On

I bet you the issue is that you're calling fixture.detectChanges() first before calling component.ngOnInit().

fixture = TestBed.createComponent(Component);
component = fixture.componentInstance;
fixture.detectChanges(); // Remove this line

The first fixture.detectChanges() you call is when ngOnInit is called and since you have not mocked this.userService.getUser() before this fixture.detectChanges(), you get that issue of cannot read property of undefined.