3

I want to compare JSON object's keys in the Jasmine. For ex: I have JSON object with two keys, I want to check if JSON contains both the via Jasmine.

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

If i have this JSON i want to check if JSON contains both the key1,key2

How can we check that in the Jasmine? If we can check the value type with the JSON key, it will be great.

hardiksa
  • 1,477
  • 1
  • 14
  • 19

2 Answers2

2

You can use Object.keys(JSONObj) to get all keys from the object. then you can do a simple toEqual or toContain assertion on the 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])
}
Sudharsan Selvaraj
  • 4,792
  • 3
  • 14
  • 22
  • It is giving 'Expected [ 'key1', 'key2' ] to contain [ 'key1', 'key2' ].' when i write the same code – hardiksa Mar 24 '17 at 07:14
0

Expanding a little on Sudharasan's answer, I wrote this to test a getter/setter of an object. It gets the keys off the initial set object and uses that to see that those keys, and only those keys, (and the right values) are on the gotten 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]]);
    }
  });
eflat
  • 919
  • 3
  • 13
  • 34