Search code examples
karate

How to match two possible values for a given field in a json with Karate


I've run into an issue with trying to validate a particular scenario in an API method call with Karate.

Essentially the response would be like: response.data.list with a list of records, and I'm trying to validate that for a specific field in each record in that list, the value either matches a string or is null.

I've tried a few different approaches but the issue I'm running into is I can't sort out how to validate all of the records in the list on this specific field.

I know I can 'match each response.data.list' to validate all the records, and can use 'contains any ['value1', 'value2'] to see if either value shows up, but I can't sort out how to check a specific field in each record of the list for either value. If I try this I get an error since it's trying to evaluate the field with a single value as if it were an array:

* match each response.data.list contains any {field: ['value1', #null]}

This second one passes, but I'm unsure from looking at my results if it actually looked over all the results or just looked at the first in the list.

* match response.data.list[*].field contains any ['value1', #null]

Does anyone have experience trying to validate something similar, or know if the 2nd code snippet there is actually evaluating all the items in the list? Any clarification would be greatly appreciated!

::Edit to add an example of the response I'm working with. In this example, I would want my code to validate that field1 was only either "123 Main St" or null::

"data": {
  "methodName": {
    "message": "found 2 records",
    "countOfRecords": 2,
    "list": [
      {
       field1: "123 Main St",
       field2: "lorem ipsum"
      },
      {
       field1: null,
       field2: "lorem ipsum"
      }
     ]
    }
   }

Solution

  • There are multiple ways, refer: https://github.com/karatelabs/karate#self-validation-expressions

    * match each response.methodName.list contains { field1: '#? _ == null || _ == "123 Main St"' }
    

    For other creative ways, refer: https://stackoverflow.com/a/62567262/143475