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

如何为带switch case的Angular函数编写单元测试并解决运行报错

问题解决

报错根因

  • 你调用extractValue方法时传入的第二个参数是字符串'isoCountry',该字符串不存在isoCountryCode属性,因此exemptionValue.isoCountryCode取值为undefined,调用undefined.toString()就触发了你遇到的类型错误。
  • 同时你编写的断言逻辑和被测函数完全无关,expect('C').toEqual('isoCountry')无法验证函数的返回值是否正确。

正确单元测试写法

首先要构造符合结构要求的exemptionValue模拟对象,包含所有switch分支需要用到的属性,再分别验证各个分支的返回值是否符合预期。

基础分支测试写法(每个分支单独验证)

it('extractValue 传入级别C时返回isoCountryCode的字符串格式', () => {
  const mockExemptionValue = {
    isoCountryCode: 86,
    districtNumber: 11,
    divisionCode: 101,
    terminalNumber: 2023
  };
  const res = component.extractValue('C', mockExemptionValue);
  expect(res).toBe('86');
});

it('extractValue 传入级别R时返回districtNumber的字符串格式', () => {
  const mockExemptionValue = {
    isoCountryCode: 86,
    districtNumber: 11,
    divisionCode: 101,
    terminalNumber: 2023
  };
  const res = component.extractValue('R', mockExemptionValue);
  expect(res).toBe('11');
});

it('extractValue 传入级别D时返回divisionCode的字符串格式', () => {
  const mockExemptionValue = {
    isoCountryCode: 86,
    districtNumber: 11,
    divisionCode: 101,
    terminalNumber: 2023
  };
  const res = component.extractValue('D', mockExemptionValue);
  expect(res).toBe('101');
});

it('extractValue 传入级别T时返回terminalNumber的字符串格式', () => {
  const mockExemptionValue = {
    isoCountryCode: 86,
    districtNumber: 11,
    divisionCode: 101,
    terminalNumber: 2023
  };
  const res = component.extractValue('T', mockExemptionValue);
  expect(res).toBe('2023');
});

优化参数化写法(减少重复代码)

可以用参数化方式一次覆盖所有分支,减少冗余代码:

it('extractValue 所有分支返回对应属性的字符串结果', () => {
  const mockExemptionValue = {
    isoCountryCode: 86,
    districtNumber: 11,
    divisionCode: 101,
    terminalNumber: 2023
  };
  // 测试用例格式:[输入级别, 预期输出结果]
  const testCases = [
    ['C', '86'],
    ['R', '11'],
    ['D', '101'],
    ['T', '2023']
  ];

  testCases.forEach(([inputLevel, expectedRes]) => {
    const actualRes = component.extractValue(inputLevel, mockExemptionValue);
    expect(actualRes).toBe(expectedRes);
  })
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:45:05