单元测试 - ngOnInit中的服务:错误'地图不是一个功能'

时间:2017-04-12 15:38:07

标签: unit-testing angular jasmine

我尝试使用Jasmine& amp; Karma,但是当我想测试我的服务是否已经在ngOnInit()中调用时,我得到一个我不明白的错误:

Failed: Uncaught (in promise): TypeError: tagelers.map is not a function
TypeError: tagelers.map is not a function
    at tagelerService.getTagelers.then (http://localhost:9876/base/src/test.ts?779e448059ef6555f776fac9a62a71930cc82ee7:68007:38)
    ....

我的组件如下所示:

import ..

@Component({
  selector: 'app-group-details',
  templateUrl: 'group-details.component.html',
  styleUrls: ['group-details.component.css'],
})

export class GroupDetailsComponent implements OnInit {
  @Input()
  tageler: Tageler;
  tagelers: Tageler[];
  group: Group;

  constructor(
    private route: ActivatedRoute,
    private groupService: GroupService,
    private tagelerService: TagelerService) {
  }

  ngOnInit() {
    console.log("Init Details");
    this.route.params
      .switchMap((params: Params) => this.groupService.getGroup(params['id']))
      .subscribe(group => this.group = group);

    this.tagelerService
      .getTagelers()
      .then((tagelers: Tageler[]) => {
        this.tagelers = tagelers.map((tageler) => {
          if (!tageler.title) {
            tageler.title = 'default';
          }
          return tageler;
        });
      });
  }
}

这就是tagelerService中方法的样子:

getTagelers(): Promise<Tageler[]> {
return this.http.get(this.tagelersUrlGet)
  .toPromise()
  .then(response => response.json() as Tageler[])
  .catch(this.handleError);
}

这个我的测试是我的spec.ts文件失败了:

it('should get tagelers when ngOnInit is called', async(() => {
    spyOn(tagelerService, 'getTagelers').and.returnValue(Promise.resolve(Tageler));
    component.ngOnInit();
    fixture.detectChanges();
    expect(tagelerService.getTagelers).toHaveBeenCalled();
}));

有谁知道为什么有一个&#39; .map不是一个功能&#39;错误?我想这个问题是&#39; spyOn&#39; (它不会返回我需要的东西),但我不知道如何改变它。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您正尝试使用Tageler类(只有Function,没有map方法)来解决问题。

and.returnValue(Promise.resolve(Tageler));

您需要使用实际的Tageler实例数组

来解决

问题在于ngOnInit

this.tagelers = tagelers.map((tageler) => {

tagelers是一个函数(Tageler类),但它需要一个数组