我尝试将此正则表达式设置为身份验证给定步骤,其中包含两个可选参数:
Given(/^I log in as ([A-Za-z\-]+)(?: with the contract ((?:.(?!for the protal))+))?(?: for the protal (.*))?$/,
function(user, contract, portal, callback) {
console.log({user, contract, portal});
}
);
Cucumber-js 无法检测到第二个可选参数,即使它成功地将表达式匹配到具有一个、两个或三个参数的给定句子。
我将 .(?!for the protal)
放在第二个参数中,以在第三个参数(门户)最终开始时结束它,因为契约(Contract)列表并不详尽。
这是三种情况下我得到的输出:
Given I log in as tester1
user: tester1,
contract: undefined,
portal: undefined
OK
Given I log in as tester1 with the contract contract1
user: tester1,
contract: undefined,
portal: undefined
KO
Given I log in as tester1 with the contract contract1 for the protal portal1
user: tester1,
contract: portal1,
portal: undefined
KO
我认为在 cucumber-js 中检测这部分正则表达式 .(?!for the protal) 存在问题,因为在 Java 中工作的表达式完全相同。除此之外,当仅提及第一个和第三个参数时,Java 中的 Cucumber 成功地将第二个参数设置为未定义(但这是另一个问题)。
谢谢!
最佳答案
您需要执行此步骤的 3 个版本,一个有契约(Contract),一个有契约(Contract)和门户网站,一个没有。
Given(/^I log in as ([\w-]+)$/,(user)=>{
// log in
});
Given(/^I log in as ([\w-]+) with the contract ([\w-]+)$/, (user, contract) => {
// log in with contract
});
Given(/^I log in as ([\w-]+) with the contract ([\w-]+) for portal ([\w-]+)$/, (user, contract, portal)=>{
// log in with contract for portal
});
可选参数与 Cucumber 无关,这是一个小问题,但由于这些步骤都在尝试实现不同的目标(我知道,从技术上讲,它们都在尝试登录,但我的意思是他们以不同的方式登录),使用具有多个选项的相同步骤来完成它可能意味着您的步骤试图实现太多目标。
您的步骤定义无疑包含多个条件语句,这些语句依赖于通过的参数。为什么不通过将它们定义为不同(但相似)的步骤来简化它?
如果您觉得它们足够相似,将代码保留在同一位置的解决方法是创建一个接受 3 个参数的登录函数,其中 2 个参数是可选的。
function logIn(user, contract = null, portal = null){
// do your single step stuff here
}
Given(/^I log in as ([\w-]+)$/,(user)=>{
return logIn(user);
});
Given(/^I log in as ([\w-]+) with the contract ([\w-]+)$/, (user, contract) => {
return logIn(user, contract);
});
Given(/^I log in as ([\w-]+) with the contract ([\w-]+) for portal ([\w-]+)$/, (user, contract, portal)=>{
return logIn(user, contract, portal);
});
关于javascript - 在 cucumber-js 中检索在特定字符串之前结束的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50504052/