0

I'm trying to write a test for the following method call in the ngOnInit method of my component:

person: Person;

ngOnInit(){
 this.service.person.asObservable().subscribe(data => {
   this.methodCall(data);
 }
}

Here is my service:

person = new Subject<Profile>();

updatePerson(){
   return httpService.put(data)
    .subscribe(response => {
    this.person.next(response);
  })
}

Here is my test for the component:

it ('should update person when service.updatePerson is invoked', () => {
    const service = TestBed.get(Service);
    const response = {
      'profile': {
        'fullName': 'John Manny',
        'email': 'john.manny@yahoo.com',
       }
     };
     const spy = spyOn(service, 'updatePerson').and.returnValue(of(response));

     component.ngOnInit();
     expect(spy).toHaveBeenCalled();
});

My test keeps failing? How can test the invocation of the observable call in my component?

jo_va
  • 13,504
  • 3
  • 23
  • 47
user1324418
  • 267
  • 1
  • 6
  • 14
  • What have you tried so far? StackOverflow expects you to [try to solve your own problem first](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), as your attempts help us to better understand what you want. Please edit the question and add your attempted `.spec` file. – dmcgrandle Feb 08 '19 at 02:29
  • You are spying on `updatePerson`, but it's never called in the provided code. Since your expecting the method to have been called, and it isn't, the test fails. Unless you have a requirement to cache it, I wouldn't store the response data in the service. Instead, I would just have `ngOnInit` call the `service.updatePerson` method directly. That change should make the provided spec pass. – The Head Rush Feb 08 '19 at 14:43

0 Answers0