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

时间:2018-07-17 12:06:50

标签: karate

我试图使用下面的空手道代码将变量'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

1 个答案:

答案 0 :(得分:0)

由于您没有提供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循环。

相关问题