Javascript Nightwatch:使用自定义命令迭代所有select标记

Javascript Nightwatch:使用自定义命令迭代所有select标记,javascript,selenium,nightwatch.js,Javascript,Selenium,Nightwatch.js,我已经为我在Nightwatch中的UI测试创建了这个自定义命令。全文如下: exports.command = function(element, callback) { var self = this; try { this.waitForElementVisible('body', 15000); console.log("trying.."); window.addEventListener('load', function() { v

我已经为我在Nightwatch中的UI测试创建了这个自定义命令。全文如下:

exports.command = function(element, callback) {

  var self = this;

  try {

    this.waitForElementVisible('body', 15000);
    console.log("trying..");
    window.addEventListener('load', function() {

      var selects = document.getElementsByName("select");
      console.log(selects);

    }, false);


  } catch (err) {
    console.log("code failed, here's the problem..");
    console.log(err);
  }

  this
    .useXpath()
  // click dropdowns
  .waitForElementVisible(element, 15000)
    .click(element)
    .useCss()
    .waitForElementVisible('option[value="02To0000000L1Hy"]', 15000)
  // operation we want all select boxes to perform
  .setValue('option[value="02To0000000L1Hy"]', "02To0000000L1Hy")
    .useXpath()
    .click(element + '/option[4]');

  if (typeof callback === "function") {
    callback.call(self);
  }
  return this; // allows the command to be chained.

};

我试图做的是在加载页面后,检索所有的选择框并对它们执行相同的操作。除了try/catch块中的代码外,其他一切都正常工作。我一直在获取“[ReferenceError:window未定义]”,我不确定如何通过它。

全局范围中未定义“window”属性,因为它是通过命令行节点运行的,而不是在浏览器中运行的,正如人们最初可能认为的那样


您可以尝试使用Nightwatch API中的这个脚本,但我建议使用Selenium协议API

您还可以使用我在实际页面上需要注入一点JavaScript时使用的命令。正如@Steve Hyndig所指出的,您的测试是在节点上运行的,而不是在实际的浏览器窗口上运行的(有些令人困惑,因为在运行测试时窗口通常是打开的!当然,除非使用PhantomJS进行无头测试)

下面是一个示例自定义命令,它将根据您的原始帖子向页面注入一些JavaScript:

exports.command = function(callback) {
  var self = this;

  this.execute(function getStorage() {
    window.addEventListener('load', function() {
      let selects = document.getElementsByName('select');
      return selects;
    }
  },

  // allows for use of callbacks with custom function
  function(result) {
    if (typeof callback === 'function') {
      callback.call(self, selects);
    }
  });

  // allows command to be chained
  return this;
};
您可以使用以下语法从测试中调用它,包括一个可选回调来处理结果:

client
  .setAuth(function showSession(result) {     
    console.log(result);    
});
您可以选择只在自定义函数内部执行工作,但由于Nightwatch的异步特性,有时如果我不在回调中嵌套内容,我会遇到问题,因此这更安全

祝你好运