使用Selenium步骤定义从CucumberJS执行回调

时间:2015-08-12 23:02:50

标签: javascript node.js selenium phantomjs cucumberjs

我正在尝试使用Selenium和PhantomJS的CucumberJS。我已成功built a World object using this StackOverflow answer作为指南。

所以现在我正在测试一些基本的步骤定义,但是对于如何在步骤结束时执行回调有些困惑。这非常有效:

module.exports = function () {
  this.World = require("../support/world.js").World;

  this.Given(/^I am visiting Google$/, function (callback) {
    this.driver.get('http://www.google.com')
        .then(function() {
          callback();
        });
  });
};

驱动程序访问Google.com并且在加载所请求的文档之前不会触发回调。但是我发现这个语法有点罗嗦,所以我想也许我可以在我的第一个承诺之后直接将callback传递给then(),如下:

module.exports = function () {
  this.World = require("../support/world.js").World;

  this.Given(/^I am visiting Google$/, function (callback) {
    this.driver.get('http://www.google.com')
        .then(callback);
  });
};

然而,这失败了,似乎是console.log callback。这是输出:

  Scenario: Googling           # features/theGoogle.feature:6
    Given I am visiting Google # features/theGoogle.feature:7
      [object Object]


    (::) failed steps (::)

    [object Object]

这里发生了什么?我期待callback可以简单地传递给then()函数并在履行承诺后执行。为什么将它包装在一个匿名函数中才能使它工作?

1 个答案:

答案 0 :(得分:1)

正在发生的事情是使用callback的参数调用driver.get().then

换句话说,这是发生的事情:

this.driver.get('http://www.google.com')
  .then(function(result) {
    callback(result);
  });

问题在于,如果使用某个东西作为其第一个参数调用回调,则黄瓜的回调将考虑失败,因为它应该是callback(new Error('Something went wrong'))中的错误。

对我而言,这足以完全禁止使用回调。 Selenium是完全导向的承诺,只有当你希望生活更轻松时,你才应该遵守诺言。这是完美的,因为cucumber.js接受promises而不是回调,所以这是最好的做事方式:

// Be sure to omit the last parameter of the function, usually "callback"
this.Given(/^I am visiting Google$/, function () {
  return this.driver.get('http://www.google.com');
});

如果承诺最终被拒绝,则该步骤将失败,或者如果承诺已满,则继续执行下一步。但是在这两种情况下,黄瓜都会等待最后的承诺,所以你需要做的就是返回任何步骤的最后一个承诺,因为Selenium只会解决/拒绝之前的承诺。一切看起来都不是很好吗?