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);
}
);
}
```
I bet you the issue is that you're calling
fixture.detectChanges()first before callingcomponent.ngOnInit().The first
fixture.detectChanges()you call is whenngOnInitis called and since you have not mockedthis.userService.getUser()before thisfixture.detectChanges(), you get that issue of cannot read property of undefined.