Search code examples
jsonkaratejsonpath

Karate API framework - How to assert the empty value of a key and if that value is empty then assert that some other key should not present


Is there any way in Karate through which I can check that if any value is coming as empty string then some other key in the response should not present -

For example if you see below sample json response one of the results[*].source.Descriptions[*].text is empty and at the same node the preview results[*].source.preview is not present

So any straight forward solution in karate which can check that if Descriptions.text is '' then preview should not be present at that node

 {
    "total": 10,
    "count": 10,
    "results": [
        {
            "id": "1",
            "source": {
                "type": "general",
                "Description": [
                    {
                        "text": ""
                    }
                ]
            }
        },
        {
            "id": "2",
            "source": {
                "type": "general",
                "preview": "Your name",
                "Description": [
                    {
                        "text": "Your name is Karate"
                    }
                ]
            }
        }
    ]
}

Solution

  • Here you go. Read the docs in case anything is not clear:

    * def isValid = function(x){ var desc = x.source.Description[0].text; return desc === '' ? !x.preview : true }
    * match each response.results == '#? isValid(_)'