You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript多参数函数问题:独立文件轮询函数的Feature调用咨询

嘿,我先帮你梳理下这个JavaScript函数里的小问题,再告诉你怎么在Feature文件里正确调用它~

第一步:修正函数里的变量错误

你写的代码里有个明显的小bug:greeting这个变量根本没定义,你应该是想用前面获取到的sCode对吧?另外我也优化了日志内容,让调试时更清晰,修正后的函数如下:

function polling_orderitem_CNCL(source_id, condition) { 
  var i = 0; 
  while (i < 10) { 
    var result = karate.call('./polling/get_order_item.feature', {SourceId : source_id}); 
    var sCode = result.response.data.attributes.statusCode; 
    karate.log('Poll response status code:', sCode); // 替换未定义的greeting为sCode
    if (sCode == condition) { // 同样替换成正确的变量
      karate.log('Condition satisfied, exiting polling loop'); 
      return sCode; // 返回状态码,方便后续Feature里做断言验证
    } 
    karate.log('Condition not met, sleeping for 1 second...'); 
    java.lang.Thread.sleep(1000); 
    i++; 
  }
  // 如果10次轮询都没满足条件,抛出异常终止测试
  karate.fail('Polling timed out after 10 attempts - status code never matched: ' + condition);
}

第二步:在Feature文件中调用函数

首先把这个修正后的函数保存到一个独立的.js文件里,比如命名为polling-utils.js。然后在你的Feature文件里先加载这个函数,之后就能直接调用了,举个完整的示例:

Feature: Verify Order Item Cancellation Status
  Background:
    # 加载JS工具函数,注意路径要和你的文件位置匹配
    * def polling_orderitem_CNCL = read('classpath:utils/polling-utils.js')

  Scenario: Wait for order item to cancel
    # 定义你要测试的sourceId和目标状态码
    * def targetSourceId = 'ORD-12345'
    * def expectedStatusCode = 'CNCL'

    # 调用轮询函数,直到状态符合预期或超时
    * polling_orderitem_CNCL(targetSourceId, expectedStatusCode)

    # 可选:再次调用接口做最终断言,确保状态确实符合要求
    * def finalOrderStatus = karate.call('./polling/get_order_item.feature', {SourceId: targetSourceId})
    * match finalOrderStatus.response.data.attributes.statusCode == expectedStatusCode

额外小提醒

  • 确保get_order_item.feature的路径是正确的,既可以用相对当前Feature文件的路径,也可以用classpath:开头的绝对路径
  • 如果你的Karate版本比较新,也可以试试内置的karate.retry()方法来简化轮询逻辑,不过你自己写的循环逻辑完全没问题,灵活性更高
  • 日志内容尽量明确,这样调试时能清楚看到每一次轮询的结果

内容的提问来源于stack exchange,提问作者Jawad Kalia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:45:01