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.

4

2 回答 2

2

您可以使用Object.keys(JSONObj)从对象中获取所有键。然后你可以对结果做一个简单的toEqualtoContain断言。

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])
}
于 2017-03-23T21:26:37.700 回答
0

扩展了 Sudharasan 的回答,我写了这个来测试对象的 getter/setter。它从初始集合对象中获取键,并使用它来查看那些键,并且只有那些键(和正确的值)在获取的对象上。

  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]]);
    }
  });
于 2018-01-10T23:20:09.103 回答