0

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 Answers1

0

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.

AliF50
  • 16,947
  • 1
  • 21
  • 37
  • Hi,so, every time i call fixture.detectChanges(), the lifecycle is executed? – Ricardo Tovar Aug 10 '22 at 15:53
  • Isn't it best practice to place it beforeeach? – Ricardo Tovar Aug 10 '22 at 16:17
  • Hello, not every time. The first time. Every time after the first time, the HTML just gets updated with the new properties. – AliF50 Aug 10 '22 at 16:17
  • It could be best practice to place it `beforeEach` so make sure everything in the `ngOnInit` is mocked properly before this `fixture.detectChanges()` or else you will have issues like your question. – AliF50 Aug 10 '22 at 16:18
  • Hi,so, every time i call fixture.detectChanges(), the lifecycle is executed? – Ricardo Tovar Aug 10 '22 at 22:35
  • The `ngOnInit` lifecycle is not executed on every `fixture.detectChanges()`. The `ngOnInit` lifecycle is executed on the FIRST `fixture.detectChanges()`. – AliF50 Aug 11 '22 at 12:43
  • Hi, So , for example If my ngOninit call a api for get a user, in my test how could I test that? making a spyService before fixture.detectChanges() :? `` – Ricardo Tovar Aug 15 '22 at 04:52
  • That's correct, make the spy return something before the first `fixture.detectChanges().` – AliF50 Aug 15 '22 at 12:45