0

If I have the following delete method in a component

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent {
  this.heroes = [];

  constructor(private heroService: HeroService) { }

  delete(hero: Hero): void {
    this.heroes = this.heroes.filter(h => h !== hero);
    this.heroService.deleteHero(hero).subscribe();
  }
}

How can I test in Jasmine that the delete hero method has called subscribe in a test.

Here is a test which ensures deleteHero was called with a specific argument, but I'm unsure how to check for a subscription.

// Interaction Test
it('should call deleteHero with the specificed argument', () => {
  // arrange
  mockHeroService.deleteHero.and.returnValue(of(true));
  component.heroes = HEROES;

  // act
  component.delete(HEROES[2]);

  // assert
  expect(mockHeroService.deleteHero).toHaveBeenCalledWith(HEROES[2]);
});
Michael Martinez
  • 171
  • 1
  • 3
  • 10
  • What is inside the `subscrbe()`. ? Don't you want to get the delete response inside the subscribe method? – Anuradha Gunasekara Jul 06 '18 at 10:57
  • I'm working through a unit testing course on pluralsight and they asked how you would check that the subscribe method was called. the component (which does nothing in the subscribe method) was the component method they used in the tutorial. Seems silly, sure. but was still curious how I would check that subscribe was called. – Michael Martinez Jul 06 '18 at 11:04
  • 1
    @MichaelMartinez as a side note, you should remove the hero once your call has been made. If the call fails, you will have removed the hero on the front-end, but not on the back-end. –  Jul 06 '18 at 11:11

1 Answers1

5

You're going to need two spies :

it('should call deleteHero with the specificed argument', () => {
  const resMock = of(true);
  spyOn(resMock, 'subscribe'); // No need to .and since you do nothing after it
  mockHeroService.deleteHero.and.returnValue(resMock);
  component.heroes = HEROES;

  component.delete(HEROES[2]);

  expect(mockHeroService.deleteHero).toHaveBeenCalledWith(HEROES[2]);
  expect(resMock.subscribe).toHaveBeenCalledWith(); // check if no callback is given
});