【问题标题】:How to use parameters in one function in another using Javascript如何使用Javascript在另一个函数中使用参数
【发布时间】:2017-08-18 13:45:08
【问题描述】:

我正在使用 Protractor 和 Cucumber 执行自动化。我有一个场景,我需要在函数 B 中使用函数 A 的输出。在不使用 cucumber 的情况下,我可以使用 then 扩展函数。但是使用黄瓜我无法做到这一点。

有人可以建议如何使用黄瓜来做到这一点。

功能A

Then('abc', function (done) {
  search.cityCountyDropDown.click();
  search.cityCounty.count().then(function(count) {
    search.cityCountyCount = count;
    search.randomCityCountyIndex = (
      1 + Math.floor(Math.random() * (search.cityCountyCount - 1))
    );
  })
  .then(function() {
    search
      .cityCounty
      .get(search.randomCityCountyIndex)
      .getText()
      .then(function(cityCountyLabel) {
        search.selectCityCountyLabel(cityCountyLabel);
        console.log(cityCountyLabel);
        done();
      });
  });
});

功能 B

Then('defij', function (done) {
  console.log(cityCountyLabel);
  done();
});

我想在函数 B 中使用cityCountyLabel

这是我的 pageObject.js 文件。

var SearchPage = function () {
    this.Category = element(by.css('[href="/abc/"]'));
    this.Header = element(by.id('abc'));

    this.cityCountyDropDown = element(by.id('abc'));
    this.cityCounty = element.all(by.xpath("//*[@id='abc']/dd/ul/li"));

    this.cityCountyCount;
    this.randomCityCountyIndex;

    this.selectCityCountyLabel = function (cityCountyLabel) {
        element(by.xpath(".//*[@id='abc']/dd/ul/li[text()='" + cityCountyLabel + "']")).click();
    };


    this.submitButton = element(by.css('input.btn-search'));
    this.searchResults = element.all(by.xpath("//*[@id='abc']/tbody/tr/td[1]/div[@class='abc']"));

    this.searchResultsCount;
    this.randomSearchResultsIndex;

    this.randomSearchResult = function (randomSearchResultsIndex, searchResult) {
        return element(by.xpath(".//*[@id='abc']/tbody/tr/td[1]/div[@class='abc'][" + randomSearchResultsIndex + "]/div[1]/h2/a"));
    }

    this.addressRegex;
}

module.exports = new SearchPage();

【问题讨论】:

    标签: javascript selenium-webdriver gruntjs protractor cucumber


    【解决方案1】:

    在 cucumber 中,您使用World 在步骤之间传递数据,在步骤中可以使用this。示例代码:

    Then('abc', function (done) {
         this["cityCountyLabel"] = "data";
         done();
    });
    
    Then('defij', function (done) {
         // this will print out: "data"
         console.log(this["cityCountyLabel"]);
         done();
    });
    

    【讨论】:

    • 谢谢@Tomas,就我而言,cityCountyLabel 总是生成一个随机值。你能建议我在这种情况下如何使用吗?我可以用这种格式Then('abc', function (done) { this["cityCountyLabel"] ; done(); });
    • 您使用 this["cityCountyLabel"] 的方式与在示例中使用 cityCountyLabel 变量的方式相同
    • 所以我可以使用上面提到的格式.. 否则,如果你能提供一个例子。
    • 您提供的尝试过的示例,但它返回未定义。
    猜你喜欢
    • 1970-01-01
    • 2020-03-09
    • 2021-07-03
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多