Unable to Parse the variable value to the array va

2019-08-11 20:14发布

问题:

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:

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.



标签: karate