Search code examples
automationkarate

How to use a variable inside a js function which is declared outside a js function in karate framework


Here is what I'm trying to achieve: I've declared one variable outside of js function in karate code. This variable is an array of objects and already consists of values. I've written a js function inside of an eval tag and within that function there's a for loop that uses this array.

* def results  = response.results
* eval
"""
Var md;
for(var id in results){
md = results[id].data
console.log(md)
}
"""

But in console [object, Object] is getting printed. I'm assuming the for.loop is not able to understand the array name I want to loop on.enter code here


Solution

  • Best practice is never to use a JS for loop in Karate. Refer to this section of the docs: https://github.com/karatelabs/karate#loops

    Here's how I would do it:

    * def response = { results: [1, 2, 3] }
    * response.results.forEach(x => karate.log(x))
    

    Work with someone who knows JS well if needed. Please assume that karate does not support the kind of JS you are doing. That has nothing to do with testing APIs.