Jasmine , Karma - Ignore ids from result object while comparison using toEqual

457 views Asked by At

I am writing some test cases for a function that takes in an input and provides a modified output object.

My mock response is :-

mockResponse = {
       "id":1,
       "value":23,
       "name":"first",
       "children":[
          {
             "id":2,
             "value":24,
             "name":"second",
             "children":[
                
             ]
          }
       ]
    }

This function gives me an output with different ids because I have a different logic for generation of ids in that function

 actualResponse =   {
       **"id": 2342342,**
       "value":23,
       "name":"first",
       "children":[
          {
             **"id":242,**
             "value":24,
             "name":"second",
             "children":[
                
             ]
          }
       ]
    }

I have many such mock objects that I need to compare with the result.

Is there a way I can ignore these ids while writing my jasmine test case ?

expect(actualResponse).toEqual(mockResponse);

Fow now I am spying on my uniqueId generator function and returning a hard coded value and using the same value as ids while forming the mock response object. But I believe there should be a better way to do this by ignoring the ids in the toEqual comparison.

EDIT 1:

I've used loadsh's isEqualWith to compare both the objects excluding the id's and saved the boolean response in a variable.

const areObjectsEqual = isEqualWith(mockResponse, actualResponse, (value1, value2, key) => {
            return key === 'id' ? true : undefined;
          });


expect(areObjectsEqual).toBeTrue();  //Successful test case. 

Do you believe this way of comparing instead of relying on jasmine and Karma's toEqual a bad practice?

Also, will this have an impact on code coverage?

0

There are 0 answers