【问题标题】:Angular Jasmine this service method is a not a functionAngular Jasmine 这个服务方法不是一个函数
【发布时间】:2021-01-13 23:52:48
【问题描述】:

我试图让一个服务方法在单元测试中通过,但是它一直失败:

“TypeError:this.eventsService.getEvent 不是函数”

我的组件内的代码:

constructor(
 private eventsService: EventsService
)

this.subscriptions.add(
  this.eventsService.getEvent().subscribe(events => {
    this.events = events;
    this.soSomeMethod();
  })
);
// Also have a V2 method, unsure if it matters but adding it for clarity
this.subscriptions.add(
  this.eventsService.getEventV2().subscribe(eventsV2 => {
    this.eventsV2 = eventsV2;
    this.soSomeMethod();
  })
);

这是有问题的服务:

  public getEvent(): Observable<event[]> {
    return combineLatest(this.store.select(getEventStore), this.store.select(getEvents)).pipe(
      map(state => {
        // do something 
      })
    );
  }
  public getEventV2(): Observable<event[]> {
    return combineLatest(this.store.select(getEventStore), this.store.select(getEvents)).pipe(
      map(state => {
        // do something 
      })
    );
  }

我的测试在提供者内部有方法:

    { provide: EventsService, useValue: { getEvent: () => of([])}},
    { provide: EventsService, useValue: { getEventV2: () => of([])}},

【问题讨论】:

    标签: javascript angular typescript jasmine


    【解决方案1】:

    问题是 Angular 正在使用您为 EventsService 提供的最后一个 provider

    要修复它,请执行以下操作:

    { provide: EventsService, useValue: { getEvent: () => of([]), getEventV2: () => of([]) } },
    // remove the two instances of EventsService and keep it to one.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-08
      • 1970-01-01
      • 2014-05-21
      • 1970-01-01
      • 1970-01-01
      • 2019-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多