0

How can I write a test for an empty value of a specific JSON name pair. For example I have this JSON:

{
    "data": {
        "sectionGroupName": "PPConfig:APIMethod",
        "sections": {}
    },
    "success": true,
    "errorMessage": ""
}

I want to check if sections is empty, like it is in this case. I have other successful tests written like this:

tests["Status code is 200"] = responseCode.code === 200;
var body = JSON.parse(responseBody);
tests["Success Response"] = body.success === true;
tests["No Error message"] = body.errorMessage === "";
tests.Data = body.data.sectionGroupName === "PPConfig:APIMethod";

But I haven't been able to find successful test code for checking if the value of a specific name is an empty dictionary. Can someone help me with this as an example please?

2 Answers2

0

You can get the list of properties of sections and test its length.

let sectionKeys = Object.keys(body.data.sectionGroupName)
if(sectionKeys.length){
  //Proceed with section
} else {
  //Proceed when it's empty
}

See Object.keys()

Techniv
  • 1,967
  • 15
  • 22
0

from this link to check if it's a dictionary (use your 'sections' as v)

function isDict(v) {
    return !!v && typeof v==='object' && v!==null && !(v instanceof Array) && !(v instanceof Date) && isJsonable(v);
}

Then check that it is empty (from this other link) use:

function isEmpty(obj) { 
   for (var x in obj) { return false; }
   return true;
}

That should work

A.Joly
  • 2,317
  • 2
  • 20
  • 25