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

如何编写Angular中offerStatus函数switch语句的单元测试用例?

Angular中offerStatus函数的单元测试用例

针对你提供的offerStatus函数,以下是基于Jasmine(Angular默认测试框架)编写的单元测试,覆盖所有分支逻辑:

import { OfferComponent } from './offer.component';

describe('OfferComponent', () => {
  let component: OfferComponent;

  beforeEach(() => {
    component = new OfferComponent();
  });

  describe('offerStatus', () => {
    it('返回"Canceled"当状态为"CANCELLED"', () => {
      expect(component.offerStatus('CANCELLED', '')).toBe('Canceled');
    });

    it('返回"Discovery"当状态为"DISCOVERY"', () => {
      expect(component.offerStatus('DISCOVERY', '')).toBe('Discovery');
    });

    it('返回"Implementation"当状态为"IMPLEMENTATION"', () => {
      expect(component.offerStatus('IMPLEMENTATION', '')).toBe('Implementation');
    });

    it('返回"Review"当状态为"REVIEW"', () => {
      expect(component.offerStatus('REVIEW', '')).toBe('Review');
    });

    it('返回"Review"当状态为"IN_REVIEW"', () => {
      expect(component.offerStatus('IN_REVIEW', '')).toBe('Review');
    });

    it('返回"OnHold-Manual"当状态为"ON_HOLD"且reason为"Manual processing necessary"', () => {
      expect(component.offerStatus('ON_HOLD', 'Manual processing necessary')).toBe('OnHold-Manual');
    });

    it('返回"On Hold"当状态为"ON_HOLD"且reason不为指定值', () => {
      expect(component.offerStatus('ON_HOLD', 'Other Reason')).toBe('On Hold');
      expect(component.offerStatus('ON_HOLD', '')).toBe('On Hold');
      expect(component.offerStatus('ON_HOLD', null)).toBe('On Hold');
    });

    it('当状态不在switch分支中时返回undefined', () => {
      expect(component.offerStatus('INVALID', '')).toBeUndefined();
      expect(component.offerStatus('', '')).toBeUndefined();
      expect(component.offerStatus(null, '')).toBeUndefined();
    });
  });
});

测试说明

  • 覆盖了switch语句的所有分支,包括REVIEW和IN_REVIEW两个状态返回相同结果的情况
  • 针对ON_HOLD的嵌套条件,分别测试了匹配指定reason和不匹配的场景(含空值、其他字符串)
  • 补充了未定义状态的边界测试,确保函数在非预期输入下的行为符合逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 10:20:43