空手道特征文件中的String.split()返回异常

时间:2019-02-06 14:13:22

标签: javascript dsl karate

我不确定如何从已创建的功能中拆分响应字符串以获取响应标头的“位置”值。

我尝试过的事情

1)

Feature: Create Tariff

  Background:
  * def result = call read('../../get-user-token.feature')
  * def serviceId = call read('create-service.feature')

  Scenario: Create Tariff
    Given url 'https://app-dev.topbox.pro/tariff-svc/api/v1/tariffs'
    And header Authorization = result.response.token_type + " " + result.response.access_token
    And request
      """
      {
      serviceTypeId: '#(serviceId.responseHeaders['Location'].split('/')[1])',
      owner: 1,
      type: 0,
      pencePerMile: '69.69',
      minMileage: '1.00',
      minCost: 5,
      zoneFrom: '',
      zoneTo: '',
      fixedCost: 0
      }
      """
    When method POST
    Then status 201

这导致了...

  

IntegrationTests.TestSetup.create-tariff:create-tariff.feature:10-   net.minidev.json.parser.ParseException:位置上的意外令牌L   46。

2)

Feature: Create Tariff

  Background:
  * def result = call read('../../get-user-token.feature')
  * def serviceId = call read('create-service.feature').responseHeaders['Location'].split('/')[1]

  Scenario: Create Tariff
    Given url 'https://app-dev.topbox.pro/tariff-svc/api/v1/tariffs'
    And header Authorization = result.response.token_type + " " + result.response.access_token
    And request
      """
      {
      serviceTypeId: '#(serviceId)',
      owner: 1,
      type: 0,
      pencePerMile: '69.69',
      minMileage: '1.00',
      minCost: 5,
      zoneFrom: '',
      zoneTo: '',
      fixedCost: 0
      }
      """
    When method POST
    Then status 201

这导致了...

  

失败的功能:IntegrationTests.TestSetup.create-tariff:-unknown-:5   -JavaScript评估失败:read('create-service.feature')。responseHeaders ['Location']。split('/')1,   TypeError:无法从位于的未定义中读取属性“ Location”   行号1

注意 指定的功能“ create-service.feature”在隔离时确实可以工作,并且会生成响应标头,如下所示

Location Header Response

3 个答案:

答案 0 :(得分:3)

使用lastIndexOf代替split

* def location = responseHeaders['Location'][0]
* def serviceId = location.substring(location.lastIndexOf('/') + 1)

答案 1 :(得分:1)

您需要使用Javascript函数:https://github.com/intuit/karate#javascript-functions

* def greeter = function(name){ return 'hello ' + name }
* assert greeter('Bob') == 'hello Bob'

编辑:

* def service = { key : "someinfo/myServiceId"}
* def func = function(service){return service.key.split('/')[1]}
* def serviceId = func(service)
* match serviceId == "myServiceId"

答案 2 :(得分:1)

我认为第一个错误是由于表达式中的单引号引起的,请尝试转义

喜欢

And request
"""
{
serviceTypeId: '#(serviceId.responseHeaders.Location[0].split(\'/\')[1])',
owner: 1,
type: 0,
pencePerMile: '69.69',
minMileage: '1.00',
minCost: 5,
zoneFrom: '',
zoneTo: '',
fixedCost: 0
}
"""

编辑:刚才注意到,responseHeader中的每个值都有一个列表类型值,因此像Location [0]一样访问它

您的第二种方法应该是这样的

* def serviceId = call read('create-service.feature').responseHeaders.Location[0].split('/')[1]