You need to enable JavaScript to run this app. Jasmine单元测试报Cannot read property 'filter' of undefined错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Jasmine单元测试报Cannot read property 'filter' of undefined错误如何解决

报错根因
  • 单元测试中你 mock requestService.postRequest 接口的返回值是空对象{},但业务代码的回调逻辑中会读取返回结果的types属性并调用filter方法
  • mock 返回的data对象不存在types属性,data.types取值为undefined,调用filter方法就会触发该类型错误
解决方案

可以任选以下两种方案中的一种,也可以同时搭配使用:

方案1:调整单元测试的 mock 逻辑,贴合业务真实返回结构

修改单测中 spy 的返回值,补充上业务需要的places、types字段即可:

it('When call requestService.postRequest', () => {
  // 构造符合业务预期的返回值
  const mockRes = {
    places: [],
    types: [
      {id: 10, name: '餐饮'},
      {id: 20, name: '待过滤类型'},
      {id: 30, name: '酒店'}
    ]
  };
  spyOn(component.requestService, 'postRequest').and.returnValue(of(mockRes));
  
  component.info();
  
  expect(component.requestService.postRequest).toHaveBeenCalled();
  expect(component.requestService.postRequest).toHaveBeenCalledTimes(1);
  // 还可以补充断言验证过滤逻辑是否符合预期
  expect(component.types.some(item => item.id === 20)).toBeFalse();
});

方案2:给业务代码增加空值防御,兼容接口异常场景

就算线上接口返回结构异常也不会触发前端报错,提升代码鲁棒性:

info() {
  this.requestService.postRequest('Reports', 'getInfo', {})
   .subscribe(
    data => {
      this.places = data.places ?? [];
      // 用空数组兜底,避免types为undefined时调用filter报错
      this.types = (data.types ?? []).filter(obj => obj.id != 20);
      this.loading = false;
    },
    error => {
      console.log(error);
      this.loading = false;
    });
  };

内容的提问来源于stack exchange,提问作者David Angarita

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 12:24:06