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

如何在CodeceptJS+Cucumber中访问示例数据表参数?

在CodeceptJS + Cucumber中实现Docstring替换Scenario Outline变量

Cucumber JS本身不支持自动替换Docstring中的Scenario Outline变量,你需要在步骤定义里手动实现替换逻辑,核心是获取Examples中的参数值再替换占位符,以下是两种可行方案:

方案一:直接通过CodeceptJS测试上下文获取参数

在步骤定义中,通过actor().currentTest.params获取当前Examples行的所有变量,再用正则批量替换Docstring中的占位符:

const { Given } = require('cucumber');
const { actor } = require('codeceptjs');

Given('I build a message {string}', async (messageType, docString) => {
  // 获取当前场景的Examples参数
  const scenarioParams = actor().currentTest.params;
  
  // 批量替换所有<变量名>格式的占位符
  const requestBody = docString.replace(/<(\w+)>/g, (match, key) => {
    return scenarioParams[key] || match; // 找不到变量则保留原占位符
  });
  
  // 执行消息构建逻辑(替换为你的实际代码)
  await I.buildMessage(requestBody);
});

方案二:利用Cucumber World上下文存储参数

如果项目自定义了Cucumber World,可以先把参数存入World,再在步骤里调用:

  1. 定义Custom World:
// support/world.js
const { setWorldConstructor } = require('cucumber');

class CustomWorld {
  constructor({ parameters }) {
    // 保存Scenario Outline的参数
    this.scenarioParams = parameters;
  }
}

setWorldConstructor(CustomWorld);
  1. 在步骤定义中使用:
const { Given } = require('cucumber');

Given('I build a message {string}', async function (messageType, docString) {
  // 从World中读取参数并替换占位符
  const requestBody = docString.replace(/<profile>/g, this.scenarioParams.profile);
  
  // 执行消息构建逻辑
  await I.buildMessage(requestBody);
});

注意:这里必须使用普通函数(function)而非箭头函数,才能正确访问World实例的this。

两种方案都能实现你需要的变量替换,方案一更简洁,方案二更适合需要在多个步骤间共享参数的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 00:00:00