Asserting and using conditions for an array response in Karate

I've got a request that returns a list of responses in two possible structures, depending on the 'status'.

{
    "listSize": 2,
    "itemList": [
       {
            "id": ,
            "Name": "",
            "submittedOn": "",
            "Reference": null,
            "status": "Receipted",
            "response": null
        },
        {
            "id": 12345,
            "submittedOn": "",
            "Reference": null,
            "status": "Failed",
            "response": {
                "xml": "",
                "formErrors": [
                    {
                        "error_type": "",
                        "error_location":"", 
                        "error_message": "",
                    }
                ]
            }
        }, 
     ]
}

I need to check the structure for the status being either 'Receipted' or 'Failed'. In Java I would use a for loop and an if statement within it to check the response field with different criteria depending on the 'status' field. (Example below)

for (int i = 0; i < response.length; i++){
   if (response[i].status.equals("receipted")){
      //do something
   }
   else{ //failed
      //do something else
   }
}

How could I achieve something similar in Karate? Should I use a Java Helper?


Solution 1:

First, you are encouraged to write static expected results in tests. That said there are multiple ways to do this, here's one:

* def failedSchema = { xml: '#string', formErrors: '#array' }
* def isValid = function(x){ if (x.status == 'Receipted') return x.response == null; return karate.match(x.response, failedSchema).pass }
* match each response.itemList == '#? isValid(_)'

Here's another example: https://stackoverflow.com/a/62567412/143475

There are other ways to loop in Karate, but not really designed for matching: https://github.com/intuit/karate#loops

Here's an extreme example involving JSON transformation to make it easier to match: https://stackoverflow.com/a/53120851/143475

Also refer: https://github.com/intuit/karate#conditional-logic