Reputation: 191
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]);
});
Upvotes: 1
Views: 919
Reputation:
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
});
Upvotes: 6