Ad

Jasmine - TypeError: Cannot Read Properties Of Undefined (reading 'find') On Argument

- 1 answer

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!

Ad

Answer

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(...)
   }
   
}
Ad
source: stackoverflow.com
Ad