How to compare json object in Jasmine

I want to compare keys of JSON objects in Jasmine. For example: I have a JSON object with two keys, I want to check if the JSON contains both via Jasmine.

{
"key1": "value1",
"key2": "Value2"
}

      

If I have this JSON, I want to check if the JSON contains the key key1, key2

How can we verify this in Jasmine? If we can check the type of the value using the JSON key, that would be great.

+3


source to share


2 answers


You can use Object.keys(JSONObj)

to get all keys from an object. then you can make a simple statement toEqual

or toContain

a result.



var obj = {
    "key1": "value1",
    "key2": "Value2"
  };
var expectedKeys = ["key1","key2"];
var keysFromObject = Object.keys(obj);
for(var i=0; i< expectedKeys.length;i++) {
   expect(keysFromObject).toContain(expectedKeys[i])
}

      

+2


source


Expanding a bit on Sudharasan's answer, I wrote this to test the getter / setter of an object. It gets the keys from the original given object and uses that to see that those keys and only those keys (and the correct values) are on the resulting object.



  it('should test get/set MyParams', () => {
    let paramObj = {
      key1: "abc",
      key2: "def"
    };
    const objKeys = Object.keys(paramObj);

    myService.setMyParams(paramObj);
    const gottenObj = myService.getMyParams();
    const gottenKeys = Object.keys(gottenObj);

    // check that the 2 objects have the same number of items
    expect(objKeys.length).toEqual(gottenKeys.length);

    // check that a keyed item in one is the same as that keyed item in the other
    for (var i = 0; i < objKeys.length; i++) {
      expect(paramObj[objKeys[i]]).toEqual(gottenObj[objKeys[i]]);
    }
  });

      

0


source







All Articles