测试Angular组件中称为subscribe的方法

时间:2018-07-06 10:53:30

标签: angular jasmine rxjs

如果我在组件中具有以下删除方法

@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();
  }
}

我如何在Jasmine中测试delete hero方法已调用subscribe 在测试中。

这是一个确保使用特定参数调用deleteHero的测试,但是我不确定如何检查预订。

// 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]);
});

1 个答案:

答案 0 :(得分:2)

您将需要两个间谍:

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
});