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

Angular 13中如何用Jasmine测试函数内赋值给变量的方法?

解决Angular 13测试中returnFunction返回undefined的问题

错误原因

你遇到的cannot read properties of undefined (reading: 'toLowerCase')错误,本质是returnFunction依赖的ActivatedRoute在测试环境中未正确配置,导致this.route.snapshot.paramMap.get('id')返回undefined,后续调用toLowerCase()自然触发报错。另外测试代码中给compFunction传递了字符串'id',但该函数参数要求是number类型,会导致if (id)条件不成立,内部的returnFunction调用逻辑不会执行。

解决方案

方案一:正确模拟ActivatedRoute

在测试模块配置中,提供模拟的ActivatedRoute实例,确保paramMap能返回预期的id值:

import { ActivatedRoute } from '@angular/router';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { YourComponent } from './your.component'; // 替换为你的组件实际路径

describe('YourComponent', () => {
  let component: YourComponent;
  let fixture: ComponentFixture<YourComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [YourComponent],
      providers: [
        {
          provide: ActivatedRoute,
          useValue: {
            snapshot: {
              paramMap: {
                get: (key: string) => key === 'id' ? '123' : null // 设置预期的id返回值
              }
            }
          }
        }
      ]
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(YourComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it("should open foo page", () => {
    component.compFunction(1); // 传入符合类型要求的number参数
    const data = component.returnFunction();
    expect(data.toLowerCase()).toBe('123');
  });
});

方案二:直接Mock returnFunction方法

如果不需要验证returnFunction的内部逻辑,仅需让它返回预期值或验证调用情况,可使用spyOn直接模拟该方法:

it("should open foo page", () => {
  // 模拟returnFunction返回指定字符串
  spyOn(component, 'returnFunction').and.returnValue('TEST_ID');
  
  component.compFunction(1); // 传入正确类型的参数
  const data = component.returnFunction();
  
  expect(data.toLowerCase()).toBe('test_id');
  // 可选:验证returnFunction是否被调用
  expect(component.returnFunction).toHaveBeenCalled();
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 12:32:02