Search code examples
jsonjasminebddjasmine2.0

How to compare json object in Jasmine


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.


Solution

  • 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])
    }