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

Angular测试subscribe报错修复后新问题排查咨询

问题描述

跟进此前Angular单元测试相关问题,测试代码中已添加ActivatedRoute配置,TestBed配置如下:

await TestBed.configureTestingModule({
      imports: [
        HttpClientModule,
        MatDialogModule,
        BrowserAnimationsModule, 
        RouterTestingModule,
        MatSnackBarModule,
        MatTableModule,
      ],
      providers: [
        {provide: AdnimistrationSiteService, useValue: administrationServiceMock},
        {provide: VisualisationFileStorageManagerService, useValue: visualisationFileStorageManagerServiceMock},
        {
          provide: ActivatedRoute,
          useValue: {
            parent: {
              params: of({ blower_id: "test_id" })
            }
          }
        }
      ],
      declarations: [ IconsInVisualizationComponent ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
    .compileComponents();
  });

配置完成后运行测试出现新错误,报错截图如下:
报错截图
推测问题可能出自以下两个函数,咨询报错是否由参数调用toUpperCase()导致,还是存在其他问题?相关代码如下:

async getDataForIconsAndSensors() {
    this.gettingLowBlowId()
    this.getSensorsToDisplay()
    this.gettingConatiners()
    this.adnimistrationSiteService.getAllFilesWithIcons(this.lowBlowId.toUpperCase())
    .subscribe(async data => {
      this.loadedData = data;
      await this.changeIconResponse(this.loadedData);
      this.dataSource.data = this.loadedData;
    })
  }


  // 该方法用于修改或删除风机对应的图标

   changeIcons(elementFileName: string, valueToUpdate: string, blowerId: string) {
    this.adnimistrationSiteService.changeOrDeleteIcon(elementFileName, valueToUpdate, blowerId).subscribe()
    this.getDataForIconsAndSensors()
  }
问题根因

报错确实和toUpperCase()调用直接相关,核心原因是this.lowBlowId在调用toUpperCase()时为undefined,导致调用原型方法失败。
触发undefined的常见原因如下:

  • gettingLowBlowId()方法为异步逻辑(比如订阅ActivatedRoute的参数流),同步调用后直接使用this.lowBlowId时,参数还未完成赋值
  • ActivatedRoute的mock结构和实际业务代码读取参数的层级不匹配,导致gettingLowBlowId()没有正确读取到blower_id的值,赋值失败
修复方案
  1. 调整异步逻辑执行顺序:如果gettingLowBlowId()是订阅参数流的异步方法,确保参数赋值完成后再执行后续依赖lowBlowId的逻辑,参考修改:
// 假设gettingLowBlowId调整为返回Observable
async getDataForIconsAndSensors() {
    this.gettingLowBlowId().subscribe(() => {
      this.getSensorsToDisplay();
      this.gettingConatiners();
      // 增加可选链兜底,避免undefined调用报错
      const blowerId = this.lowBlowId?.toUpperCase() || '';
      this.adnimistrationSiteService.getAllFilesWithIcons(blowerId)
      .subscribe(async data => {
        this.loadedData = data;
        await this.changeIconResponse(this.loadedData);
        this.dataSource.data = this.loadedData;
      })
    })
}
  1. 校验ActivatedRoute mock结构:确认业务代码中读取blower_id的层级是否和mock一致,比如如果实际代码是直接读取this.route.params而非this.route.parent.params,需要调整mock的结构匹配真实场景。
  2. 增加变量兜底校验:所有调用toUpperCase()的变量前增加可选链、空值判断逻辑,避免边界场景报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 01:36:05