如何使用正则表达式将数据从特征文件传递到步骤定义文件?

How to pass data from the feature file to step definition file using regular expressions?

这个项目正在使用 NodeJS、Cucumber、Gherkin、Selenium。

我正在尝试传递一个存储值,或者暂时传递一个值,在此示例中,它是一个 URL 通过使用正则表达式从特征文件到步骤定义文件的值。

我想使用的功能示例(< url > 是我在其他示例中看到的猜测,但似乎不起作用)

Scenario: 0 | A User Logging In
Given I open the page with the <url> 

然后还有我的步骤定义文件

Given("/^I open the page with the url? (.*)$/"), function(next){

    driver.get("http://localhost:3000/login");
    pageElement = driver.findElement(By.id("email"));
    pageElement.sendKeys("example@email.co.uk");
    next(); 
};

我相信我的步骤定义文件是正确的,但我并不肯定。

如果您需要有关我的项目的更多信息,请告诉我我整天都在处理堆栈溢出问题,并希望尽快完成这项工作。

提前感谢您的支持, 杰克

我会尝试将您的 JavaScript 中的正则表达式更改为一个字符串,该字符串需要您传递给 Given 语句的变量:

Given('I open the page with the url {string}'), function(next) {
  //your code
}

您可以在 Gherkin Given 语句中定义变量,方法是按照通常显示的方式说明它们。例如,如果你想传入一个 string:

Scenario: 0 | A User Logging In
Given I open the page with the url "http://localhost"

会将变量 url 传递给您的 javascript 文件并包含字符串 http://localhost

整数也是如此:

Scenario: 0 | A User Logging In
Given I open the page with the url "http://localhost" and port 3000

您的 javascript 函数现在将接收 2 个变量,urlport。将它们记录到控制台,您将看到

http://localhost
3000

所以我会重新安排您的代码,如下所示:

小黄瓜:

Scenario: 0 | A User Logging In
Given I open the page with the url "http://localhost:3000/login"

JavaScript:

Given('I open the page with the url {string}', (url, next) => {
     console.log(url) // log to check the variable is being passed into the function

     driver.get(url);

     pageElement = driver.findElement(By.id("email"));
     pageElement.sendKeys("example@email.co.uk");

     next(); 
});

编辑: 您可以找到有关此特定问题的所有文档 here

下面的简短回答 - 可能对即将到来的访客有用!

适用于黄瓜中所有类型数据的通用 RegEx 模式是 - ([^"]*) 这就是完成步骤 def-

的方式

@Given("^I open the page with the ([^"]*)$") //见下面的注释* public void yourMethodName(yourdatatType yourDataVar) {

你的方法实现使用(yourDataVar) ...

}

// * 注意 - '^' 和 '$' 符号将由 cucumber 分别自动添加到任何步骤定义的开头和结尾。