Home > other >  Jasmine - TypeError: Cannot read properties of undefined (reading 'find') on argument
Jasmine - TypeError: Cannot read properties of undefined (reading 'find') on argument

Time:02-04

I'm having trouble when using .find() in an argument of a method, inside another method:

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

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

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

I have no idea how to test this with spyOn, I already have the definition in beforeEach of this.myObject as the following:

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

    ...
};

Any idea on how to tell Jasmine that there is a .find() method in the method2 arg?

Edit: Added my test in Jasmine

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

Thanks!

Edit: The problem was not in Jasmine, but in the code, as stated by the selected answer!

Thank you all!

CodePudding user response:

What happens is that to use find you first need to verify that the array is not undefined and also has a size greater than zero.

Try this:

public method2(arrayArg: any[]) {

   if (arrayArg && arrayArg.length > 0) {
      arrayArg.find(...)
   }
   
}
  •  Tags:  
  • Related