Reputation: 487
Is it possible to get the index value of a
* match response.Services[*] contains { "Service": "xyz"}
I'm looking to reuse it later for more specific tests on the same Service object.
Theres reference to a __loop
variable here but I guess I don't really understand how to apply it.
Upvotes: 1
Views: 1675
Reputation: 58058
I love your questions, you are certainly pushing Karate to the limits and I'm having to think hard to answer these as well :)
The match
does not allow you to get the "found index" or even the "loop position" which come to think of it - may be actually relevant for a match each
- but I digress.
This will take a few extra lines of code, and I really think you need to upgrade to 0.8.0. If it helps, I can confirm that there are no breaking changes (unless you use the stand-alone JAR).
The new karate.forEach()
and karate.match()
functions allow you to do very complex operations on arrays. Here are 2 examples:
Scenario: karate find index of first match (primitive)
* def list = [1, 2, 3, 4]
* def searchFor = 3
* def foundAt = []
* def fun = function(x, i){ if (x == searchFor) foundAt.add(i) }
* eval karate.forEach(list, fun)
* match foundAt == [2]
Scenario: karate find index of first match (complex)
* def list = [{ a: 1, b: 'x'}, { a: 2, b: 'y'}, { a: 3, b: 'z'}]
* def searchFor = { a: 2, b: '#string'}
* def foundAt = []
* def fun = function(x, i){ if (karate.match(x, searchFor).pass) foundAt.add(i) }
* eval karate.forEach(list, fun)
* match foundAt == [1]
If you really can't upgrade, you can write a function to manually loop over the array and the above examples should get you a solution.
Upvotes: 1