Angular8 - 测试从服务调用数组的函数

问题描述

我想测试的功能和我的测试到目前为止(不起作用)。:

canShowIt() {
  let showit = false;
  const profils = this.requestsService.userProfil;
  showit = profils.some((profil) => profil.id === this.profileDetail.id);
  return showit;
}

it('should return true',() => {
  const service = Testbed.get(RequestService);
  spyOn(service,'userProfil').and.returnValue( of ([{
    id: 1
  }]));
  const result = component.canShowIt();
  expect(service.userProfil).toHaveBeenCalled();
  expect(result).toEqual(true);
});

解决方法

如果 RequestsService#userProfil 是公共成员,则无需创建 spy。您可以在测试开始时简单地设置所需的值。

it('should return true',() => {
  this.requestsService.userProfil = [{id: 1}];
  ...

如果您将 expect(service.userProfil).toHaveBeenCalled(); 转换为私有成员并创建一个 getter method 来访问它,那么您现有的测试(没有 RequestsService#userProfil)应该可以工作。

class RequestsService {

  private _userProfil: [];
    
  public get userProfil() {
    return this._userProfil;
  }

  ...