Jasmine测试clearItem报reading 'filter' undefined错误如何解决
问题修复方案
报错根本原因
TypeError: Cannot read properties of undefined (reading 'filter') 报错是因为调用filter方法的目标值为undefined,具体有三处错误:
- 入参类型不匹配:
clearItem方法的第二个参数key是字符串类型,测试代码中错误传入了对象{key: { id: 1 }},对象作为对象属性键会自动转为[object Object],导致this.form[key]读取到不存在的属性返回undefined - 属性类型错误:
filter是数组专属方法,测试代码中给component.form.key赋值为普通对象{id:1},本身就不存在filter方法 - 未初始化
chipsOptions属性:业务代码直接调用this.chipsOptions.filter,但测试代码没有给component.chipsOptions赋初始数组值,读取直接返回undefined
修正后的测试代码
describe('clearItem()', () => { it('should clear item', () => { const item = {id:1, name:'test'}; const testKey = 'key'; // 初始化form属性,对应key的值为数组 component.form = { [testKey]: [item], id: 1, name: 'testForm' }; // 初始化chipsOptions为包含测试item的数组 component.chipsOptions = [item]; component.clearItem(item, testKey); // 校验form对应key的数组中已移除目标item expect(component.form[testKey].includes(item)).toBeFalse(); // 校验chipsOptions数组中已移除目标item expect(component.chipsOptions.includes(item)).toBeFalse(); }); });
核心调整点
- 给
clearItem传入字符串类型的key参数,匹配业务方法预期的入参类型 - 将
component.form下对应key的属性值改为数组类型,确保可以调用filter方法 - 提前初始化
component.chipsOptions为数组类型,避免读取为undefined - 修正断言逻辑,匹配业务代码的实际逻辑:
chipsOptions本身是数组不需要加['key']读取属性
内容的提问来源于stack exchange,提问作者David Angarita
相关产品推荐
相关产品推荐

