You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Karma+Jasmine测试Angular服务报错Cannot read property 'subscribe' of undefined

报错原因
  • 第一处错误在spy的配置逻辑:你在httpClientSpy.get的配置中链式调用了.and.returnValue(of(mockObj)).and.callThrough(),后面的.and.callThrough()会覆盖之前的返回值配置,改为调用spy对应的原始方法。而你用的是模拟的httpClientSpy,没有真实的get方法实现,最终getAPICard()调用后返回undefined,调用subscribe自然会抛出类型错误。
  • 第二处错误是done()的调用时机有误:你在subscribe异步回调之外同步调用了一次done(),会导致测试用例在异步请求返回前就提前结束,即使后续逻辑正确也会出现不可预期的错误。
修复方案
  1. 删除spy配置中多余的.and.callThrough(),只保留模拟返回值的配置即可,单元测试场景下不需要调用真实的http请求方法。
  2. 删除测试用例末尾多余的同步done()调用,仅在异步回调的成功/失败分支中调用done即可。
  3. 可以补充对http请求地址的校验,确保服务调用的接口地址符合预期。
修复后的测试用例代码
it('testing get api', (done: DoneFn) =>{
  const mockObj = [{
    id:'1',
    title:'title', 
    description:'description',
    image: 'imagem',
    amount: 10
  }];
  // 仅保留returnValue配置,模拟请求返回
  httpClientSpy.get.and.returnValue(of(mockObj));

  modalIndicationService.getAPICard().subscribe(
    dados => {
      expect(dados).toEqual(mockObj, 'mockObj');
      // 可新增接口地址校验逻辑,确保调用的地址符合预期
      expect(httpClientSpy.get).toHaveBeenCalledWith(modalIndicationService.GET_APICard);
      expect(httpClientSpy.get.calls.count()).toBe(1, 'one call');
      done();
    },
    done.fail
  )
})

内容的提问来源于stack exchange,提问作者Lucas Lima

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 23:48:00