首页 > 解决方案 > Cucumber JS:自定义参数类型不匹配

问题描述

我有一些使用自定义参数的步骤定义。

const assertEntity = function(name: string, operator: string, 
                                                   otherName: string) {
    console.log(`assertAttrs with ${name} ${operator} ${otherName}`);
};

Then("{name} object is {operator} {otherName}", assertEntity);

以及以下功能文件(截断)

Scenario: Compare two similar API key objects
    Given we have a new ApiKey called Red

和这样定义的参数类型

defineParameterType({
    regexp: /name/,
    transformer: function(s) {
        return s;
    },
    name: "name"
});

然而黄瓜说步骤定义未定义......

? Given we have a new ApiKey called Red
   Undefined. Implement with the following snippet:

     Given('we have a new ApiKey called Red', function () {
       // Write code here that turns the phrase above into concrete actions
       return 'pending';
     });

我相信问题出在我的正则表达式中,但我已经在示例中看到了这一点,所以我不确定如何继续。

标签: javascripttypescriptcucumberbddcucumberjs

解决方案


变形金刚的工作原理

  1. 正则表达式必须匹配参数
  2. 转换回正则表达式时,黄瓜表达式必须与步骤匹配

您可以使用任何种类的转换。例如:

Given I am on the "Home" page
Given I am on the "My Basket" page

都可以通过变压器匹配:

defineParameterType({
    regexp: /"([^"]*)"/,
    transformer(string) {
        return urls[string.replace(/ /g, "_").toLowerCase()]
    },
    name: 'page',
    useForSnippets: false
});

这里发生的转换是 url 位于各种 url 的数组中。

答案

对于您的示例,您提供的步骤定义与您提供的步骤不匹配。

但是,如果我们继续匹配这个:

Given we have a new ApiKey called "Red"

通过使用这样的步骤定义:

Given('we have a new ApiKey called {name}', function(){
     return pending
});

我们需要一个像这样的步进变压器:

defineParameterType({
    regexp: /"([^"]*)"/,
    transformer: function(s) {
        return s;
    },
    name: "name",
    useForSnippets: false
});

注意"([^"]*)"不是所有与 Cucumber 匹配的正则表达式,但它是一个相当标准的正则表达式,可以在黄瓜表达式与 3.xx 出现之前的步骤定义中找到,因此我使用的 2 个示例是跟他们。


推荐阅读