1

I am using karate framework to validate API Responses .

MY API Response is as below :

{
  "Families": [
    {
      "id1": 1,
      "names": "abc",
      "children": [
        {
          "name": "ABC",
          "age": 2
        },
        {
          "name": "ZXC",
          "age": 2
        }
      ]
    },
    {
      "id1": 2,
      "name": "buses",
      "children": [
        {
          "name": "ABCD",
          "age": 2
        },
        {
          "name": "ZXCV",
          "age": 2
        },
        {
          "name": "ZXCVF",
          "age": 2
        }
      ]
    }
  ]
}

My requirement is to validate with in children array all elements are coming in sorting order of their name .

neelaveni
  • 23
  • 6

1 Answers1

1

Please read the docs and the answers I linked before to understand this. If this looks too complicated, please use Java.

* def sort = 
"""
function(list) {
 var result = new java.util.ArrayList();
 karate.forEach(list, function(x){ karate.appendTo(result, x) });
 java.util.Collections.sort(result);
 return result;
}
"""

* def isValid = 
"""
function(x){
  var names = karate.jsonPath(x, '$.children[*].name');
  return karate.match(names, sort(names)).pass;
}
"""

* match each response.Families == '#? isValid(_)'

EDIT - in newer versions there is a karate.sort() API: https://stackoverflow.com/a/68363524/143475

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • Hi Peter , Thanks for your reply . I converted that json response to pojo and did java validations . It worked for me . thanks you . – neelaveni Sep 07 '20 at 10:35
  • Hi I just attempted this and got the following response ``` org.opentest4j.AssertionFailedError: employeeQueries.feature:59 - 'match each' failed, not a json array: + [type: JSON, value: com.jayway.jsonpath.internal.JsonContext@49962179], path: $.data ``` – Btuman Sep 24 '20 at 20:12
  • @Btuman time for you to follow this process then: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue – Peter Thomas Sep 25 '20 at 03:56