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 Answer 1

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.

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

8 Comments

Hi,so, every time i call fixture.detectChanges(), the lifecycle is executed?
Isn't it best practice to place it beforeeach?
Hello, not every time. The first time. Every time after the first time, the HTML just gets updated with the new properties.
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.
Hi,so, every time i call fixture.detectChanges(), the lifecycle is executed?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.