Search code examples
arraysjsonkarateweb-api-testing

karate: getting issues validating keys for json & array in one scenario


I am using karate for my API testing, and my current requirement is I need to write just one scenario and handle two responses as part of it. What I mean by this is my response sometimes returns a json object and sometimes returns a array of json object.

For Ex: First execution of endpoint Returns Response --

{ 
  "id": 123,
  "Name: "mytest",
  "Loc: "United States"
}

And during the next execution, the same endpoint Returns Response --

[
  { 
    "id": 123,
    "Name: "mytest",
    "Loc: "United States"
  },
  { 
    "id": 456,
    "Name: "mytest1",
    "Loc: "United Kingdom"
  }
]

My use case is to compare the keys available should be ['id','name','Loc']

Initially it was just returning a json so I was using karate.keysOf(response) and it was working fine. Now I need to handle both my usecases inside one scenario itself as it could return a json or an array of json and I need to check keys present -- if json then check just once and if array then check for all json objects inside array. I know there is way to do it separately but not sure if this could be clubbed into one use case Is there a way where I can get responseType to be either a json or an array and write two separate code with conditions or any way in which my use case could be handle.

Any help would be appreciated. Thank you in advance.


Solution

  • you can handle this using schema,

    # schmea for single json object
    * def schema = {'id':'#present', 'Name' : '#present', 'Loc' : "#present"}
    
    # determine if it an Json Array or object and set expected schema
    * def expectedSchema = (karate.match(response, "#array").pass) ? "#[] schema" : schema
    
    * match response == expectedSchema