【问题标题】:TypeError: Cannot read properties of undefined (reading 'filter') at <Jasmine>TypeError:无法在 <Jasmine> 读取未定义的属性(读取“过滤器”)
【发布时间】:2021-10-31 02:28:23
【问题描述】:

我正在为 clear Item 创建一个测试,但是当我运行测试时,我得到了错误 “TypeError:无法读取未定义的属性(读取'过滤器')在“

如何安排在测试中运行过滤器?

我的功能:

clearItem = (item, key) => {
        this.form[key] = this.form[key].filter(el => el !== item);
        this.chipsOptions = this.chipsOptions.filter(el => el !== item);
    }

我的测试:

describe('clearItem()', () => {
        it('should clear item', () => {
            let item = {id:1, name:'test'};
            component.form = { key: {id:1}, id: 1, name: 'testForm' };

            component.addItem(item);
            component.clearItem(item, {key: { id: 1 }});

            expect(component.form['key']).not.toEqual(item);
            expect(component.chipsOptions['key']).not.toEqual(item);
        });
    });

【问题讨论】:

  • 不确定您的测试是否正确? .filter 是 Array 方法,不能在 Object 上调用,其次你的 clearItem 功能键不能是对象,应该是键名
  • component.form,你也应该在测试开始时初始化component.chipsOptions

标签: angular typescript karma-jasmine


【解决方案1】:

filter 方法是为 array 对象定义的。在使用filter方法之前,请尝试检查您使用该方法的对象类型。

console.log(Array.isArray(this.form[key]));
console.log(Array.isArray(this.chipsOptions));
// When both of them are true, then you can use filter.

filter method reference

isArray method reference

【讨论】:

    猜你喜欢
    • 2021-12-26
    • 2019-03-26
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 2020-12-29
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多