【问题标题】:Jasmine - TypeError: Cannot read properties of undefined (reading 'find') on argumentJasmine - TypeError:无法读取参数上未定义的属性(读取“查找”)
【发布时间】:2022-02-03 20:52:01
【问题描述】:

在方法的参数中使用 .find() 时遇到问题,在另一个方法中:

this.myObject.myArray = [{...},{...}];

public method1(): void {
   method2(this.myObject.myArray);
}

public method2(arrayArg: any[]) {
   arrayArg.find(...)
}

我不知道如何使用 spyOn 进行测试,我已经在 this.myObject 的 beforeEach 中定义如下:

beforeEach(() => {
    myObjectMock = {
         myArray: []
    },

    ...
};

知道如何告诉 Jasmine 在 method2 arg 中有一个 .find() 方法吗?

编辑:在 Jasmine 中添加了我的测试

it('should ...', () => {
     controller.method1();
     expect(anotherObject).to.equal('another value');
})

谢谢!

编辑:问题不在 Jasmine 中,而是在代码中,正如所选答案所述!

谢谢大家!

【问题讨论】:

  • 您能详细说明一下吗?是代码本身的问题吗?还是你写的测试?除了定义myObjectMock 之外,您能否还包括您在测试文件中编写的代码来模拟数据?谢谢!
  • 你好,谢谢关心,我添加了测试方法,但是选择的答案很有帮助,这是代码端的问题,不在测试中
  • 是的,但更清晰的问题也很重要。明确的问题将在未来帮助更多的人。

标签: angular unit-testing jasmine


【解决方案1】:

发生的情况是,要使用 find,您首先需要验证数组不是未定义的并且大小也大于零。

试试这个:

public method2(arrayArg: any[]) {

   if (arrayArg && arrayArg.length > 0) {
      arrayArg.find(...)
   }
   
}

【讨论】:

  • 感谢何塞,请您进行验证! (我希望你会说西班牙语)
  • 谢谢,标记为答案!
  • No te preocupes que hablo español... Espero te haya sido de utilidad。萨卢多斯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-31
  • 1970-01-01
  • 2020-04-22
  • 2020-12-29
  • 2021-12-21
  • 2020-05-24
相关资源
最近更新 更多