基于Jasmine和Karma为Angular带switch case的转换方法编写单元测试
Angular 基于Jasmine+Karma的单元测试编写方案
首先先修正你原代码的一个语法问题:你写的case item.dataType = "Integer"是错误的赋值逻辑,会导致switch判断失效,正确写法应该是case "Integer":,下同。
测试前置说明
你的export方法依赖两个核心要素:
- 异步方法
getProducts()的执行结果 - 组件实例的
productContent属性、ProductConfig配置常量
所以测试时需要Mock异步方法,避免调用真实后端接口,直接给productContent传入测试用的模拟数据即可。
完整测试代码(对应product.component.spec.ts)
import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing'; import { ProductComponent } from './product.component'; // 替换为你实际的ProductConfig文件路径 import { ProductConfig } from './product.config'; describe('ProductComponent', () => { let component: ProductComponent; let fixture: ComponentFixture<ProductComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [ ProductComponent ] }) .compileComponents(); fixture = TestBed.createComponent(ProductComponent); component = fixture.componentInstance; fixture.detectChanges(); // Mock getProducts方法,直接返回成功的Promise,跳过真实接口调用 spyOn(component, 'getProducts').and.returnValue(Promise.resolve()); }); // 测试用例1:可转换的数字字符串按配置转为对应类型 it('should convert numeric string to corresponding type as per ProductConfig', fakeAsync(() => { // 构造测试用的原始数据,所有值都是字符串类型 component.productContent = [ { "Product Code": "1001", "Total Price": "99.9", "Discounted Price": "89.9", "Tax": "5.394" } ]; // 调用待测试的export方法 component.export(); // 等待异步逻辑执行完成 tick(); // 断言转换结果 expect(component.productContent[0]["Product Code"]).toBe(1001); expect(typeof component.productContent[0]["Product Code"]).toBe('number'); expect(component.productContent[0]["Total Price"]).toBe(99.9); expect(component.productContent[0]["Discounted Price"]).toBe(89.9); expect(component.productContent[0]["Tax"]).toBe(5.394); })); // 测试用例2:非数字字符串保持原值不转换 it('should leave non-numeric string unchanged', fakeAsync(() => { component.productContent = [ { "Product Code": "非法编码", "Total Price": "无定价", "其他字段": "测试值" } ]; component.export(); tick(); expect(component.productContent[0]["Product Code"]).toBe("非法编码"); expect(component.productContent[0]["Total Price"]).toBe("无定价"); expect(component.productContent[0]["其他字段"]).toBe("测试值"); })); // 测试用例3:空值/未定义的字段不报错,保持原值 it('should handle empty or undefined value correctly', fakeAsync(() => { component.productContent = [ { "Product Code": "", "Total Price": null, "Discounted Price": undefined } ]; component.export(); tick(); expect(component.productContent[0]["Product Code"]).toBe(""); expect(component.productContent[0]["Total Price"]).toBeNull(); expect(component.productContent[0]["Discounted Price"]).toBeUndefined(); })); });
测试运行说明
直接执行Angular CLI的测试命令即可:ng test
Karma会自动启动浏览器运行所有测试用例,输出测试结果。
内容的提问来源于stack exchange,提问作者user15784148
相关产品推荐
相关产品推荐

