2

I was trying to pass the variable 'i' value to a array index 'locations[i]' using below karate code. but throwing an error saying unable to parse. Please suggest be for any changes.

Feature: Verify Branches

Background: For loop implementation
    Given url ''
    When method GET
    Then status 200  
    * def i = 0
    * def z = $.locations[i].zip
    * def p = $.locations[i].phone
    * def fun = 
    """ 
    function(locations){ 
        for (var i = 0; i < locations.length; i++)
        {
            print(i)
            print('Element at Location ' + i +':' + p)
        }
    }
    """ 

Scenario: Validate the locations
    Given url ''
    When method GET
    Then status 200  
    * call fun p

1 Answer 1

1

It is hard to make out anything since you have not provided the value of the response. There are many things wrong here. But I'll try.

Take this line:

* def z = $.locations[i].zip

This will not work, Karate does not support variables within JsonPath by default, refer the docs: https://github.com/intuit/karate#jsonpath-filters

And I think you are un-necessarily using JsonPath where normal JavaScript would have been sufficient:

* def z = response.locations[i].zip

Also it seems you are just trying to loop over an array and call a feature. Please refer to the documentation on Data Driven Features.

Take some time and read the docs and examples please, it will be worth your time. One more tip - before I leave you to understand Karate a little better. There is a way to convert a JSON array into another JSON array should you need it:

* def fun = function(x){ return { value: x } }
* def list = [1, 2, 3]
* def res = karate.map(list, fun)
* match res == [{ value: 1 }, { value: 2 }, { value: 3 }]

So there should never be a need for you to manually do a for loop at all.

Sign up to request clarification or add additional context in comments.

3 Comments

* def z = response.locations[i].zip this code worked for me. but the complete code is not working as expected, The array count is 218 but I am able to loop only till 9 positions and then getting below message in console: '18:57:23.960 [Finalizer] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection manager is shutting down [Finalizer] DEBUG org.apache.http.impl.conn.DefaultManagedHttpClientConnection - http-outgoing-1: Close connection 18:57:23.960 [Finalizer] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection manager shut down'
@ManojKumarKotturi please see my comment above and please open a new question if needed, else this confuses everyone.
Sure will post a new question this, OK Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.