Angular+Karma-Jasmine单元测试 组件Input属性识别为undefined如何解决
问题原因
dataSource是组件的@Input输入属性,单元测试运行时没有对该属性做初始化赋值,默认值为undefined,执行makeUrl方法时访问this.dataSource.currentCriteria自然会触发空指针报错。- 现有测试用例存在设计错误:你写的
makeUrl方法内没有调用initCapital方法,对应的断言本身不可能通过,属于无效逻辑。
修复方案
首先你需要在测试执行前,给组件所有依赖的属性完成mock赋值,包括marketConditionsEnvironment、marketConditionsData以及核心的dataSource,再根据业务场景拆分测试用例:
describe('makeUrl', () => { beforeEach(() => { // Mock 所有依赖的组件属性 component.marketConditionsEnvironment = { apiRoot: 'https://test-api.example.com' }; component.marketConditionsData = { origin: {} // 按照你实际的类型定义补全mock值 }; // Mock 完整结构的dataSource component.dataSource = { currentCriteria: { createAndExecuteSearchCriteria: { searchCriteria: {} } } } as LoadsDataSource; }); // 场景1:origin.point存在时的逻辑 it('should call makeLocation and return url with origin params when origin point exists', () => { // 调整mock值匹配测试场景 component.dataSource.currentCriteria.createAndExecuteSearchCriteria.searchCriteria = { origin: { point: 'test-location-point' } }; spyOn(component, 'makeLocation').and.returnValue('&origin=LA'); const url = component.makeUrl(); expect(component.makeLocation).toHaveBeenCalledOnceWith('origin', component.marketConditionsData.origin); expect(url).toBe('https://test-api.example.com?equipment=Van&origin=LA'); }); // 场景2:origin.point不存在时的逻辑 it('should return base url without origin params when origin point not exists', () => { component.dataSource.currentCriteria.createAndExecuteSearchCriteria.searchCriteria = {}; spyOn(component, 'makeLocation'); const url = component.makeUrl(); expect(component.makeLocation).not.toHaveBeenCalled(); expect(url).toBe('https://test-api.example.com?equipment=Van'); }); });
你可以根据实际业务的类型定义调整mock属性的结构,原有测试中关于initCapital的调用断言可以直接删除,和当前测试的方法没有关联。
内容的提问来源于stack exchange,提问作者Julio Rodríguez
相关产品推荐
相关产品推荐

