jsonkarate

Match element not in JSON response


I would like to check with a Karate API test that the response does not contain an entry with ID 33.

{
"ResultSet Output": [
  {
    "ITEM_DESC": "abc",
    "ITEM_ID": 11,
  },
  {
    "ITEM_DESC": "xyz",
    "ITEM_ID": 47,
  }
],
"StatusCode": 200,
"StatusDescription": ""
}

But the response could also be "empty" like:

{
"ResultSet Output": [],
"StatusCode": 200,
"StatusDescription": ""
}

I tried:

Scenario: not in response
Given path "/api/warehouse/get"
When method Post
Then status 200
* match response not contains deep { "ITEM_ID": '33' }

but this does not work. I need to enshure that "ITEM_ID" is not in the response, OR if it's there, none if it contains 33.


Solution

  • This can be achieved pretty easily by doing the following

    First, extract the results from your response

        * def items = response['ResultSet Output']
    

    Next filter the items aray to find where any item_id is equal to 33

        * def filtered = items.filter(x => x.ITEM_ID == '33')
    

    Finally, use assert to assert that the filtered array contains 0 matches of item_id == 33

        * assert filtered.length == 0
    

    And all together would be

    Scenario: not in response
    Given path "/api/warehouse/get"
    When method Post
    Then status 200
    * def items = response['ResultSet Output']
    * def filtered = items.filter(x => x.ITEM_ID == '33')
    * assert filtered.length == 0