Search code examples
karate

'match each' one element in the array


My question about selective asserting with 'match each'. Below is a sample json body:

* def data = 


"""
{
 "companies": [
    {
     "companyDetails": {
        "name": "companyName",
        "location": {
            "address": "companyAddress",
            "street": "companyStreet"
         }
       }
    },
    {
     "companyDetails": {
        "name": "companyName",
        "location": {
            "address": "companyAddress",
            "street": "companyStreet"
         }
       }
    }
  ]
}
"""

How can we assert whether each 'companyDetails' object in the response contains a certain element, e.g. name only?

* match each data.companies contains { companyDetails: { name: '#notnull' } }

When I use above step, this returns below error:

$[0] | actual does not contain expected | all key-values did not match, expected has un-matched keys

So, is there any way we can assert only one field inside this object? For example, assert whether each companyDetails object contains name, but ignores the other elements such as location? Thanks


Solution

  • This will work:

    * match each data.companies == { companyDetails: { name: '#notnull', location: '#notnull' } }
    

    This will also work:

    * match data.companies contains deep { companyDetails: { name: '#notnull' } }
    

    Sometimes it is better to transform the JSON before a match:

    * match each data..companyDetails contains { name: '#notnull' }