无法将变量值解析为数组变量

Unable to Parse the variable value to the array variable

我试图使用下面的空手道代码将变量 'i' 值传递给数组索引 'locations[i]'。但抛出一个错误说无法解析。请提出任何更改建议。

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

由于您没有提供 response 的值,所以很难弄清楚任何东西。这里有很多错误。不过我会努力的。

走这条线:

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

这行不通,空手道默认不支持 JsonPath 中的变量,请参考文档:https://github.com/intuit/karate#jsonpath-filters

而且我认为您没有必要使用 JsonPath,而普通 JavaScript 就足够了:

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

另外,您似乎只是想遍历一个数组并调用一个功能。请参阅 Data Driven Features.

上的文档

请花点时间阅读文档和示例,这将是值得的。还有一个提示 - 在我离开之前让您更好地理解空手道。如果您需要,有一种方法可以将 JSON 数组转换为另一个 JSON 数组:

* 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 }]

所以根本不需要您手动执行 for 循环。