【问题标题】:Unit Testing - Services in ngOnInit: error 'map is not a function'单元测试 - ngOnInit 中的服务:错误“地图不是函数”
【发布时间】:2017-04-12 15:38:07
【问题描述】:

我尝试使用 Jasmine 和 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();
}));

有人知道为什么会出现“.map 不是函数”错误吗?我猜这个问题是“spyOn”的错误实现(它没有返回我需要的东西),但我不知道如何改变它。

感谢您的帮助!

【问题讨论】:

    标签: unit-testing angular jasmine


    【解决方案1】:

    您正在尝试使用您的Tageler 类(它只是一个Function,它没有map 方法)来解决。

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

    您需要使用 Tageler 实例的实际数组进行解析

    问题出在你的ngOnInit

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

    tagelers 是一个函数(Tageler 类),但它必须是一个数组

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-04
      • 2020-08-08
      • 2017-11-20
      • 2020-09-09
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 2019-03-30
      相关资源
      最近更新 更多