2016-04-25 26 views
2

我有以下用javascript编写的自定义命令for nightwatch.js。我如何将其转换为使用jquery?如何使用jquery写一个nightwatch自定义命令

exports.command = function (classId, indexIfNotZero) { 
    this.browser.execute(function (classId, indexIfNotZero) { 
     if (classId.charAt(0) == '.') { 
      classId = classId.substring(1); 
     } 
     var items = document.getElementsByClassName(classId); 

     if (items.length) { 
      var item = indexIfNotZero ? items[indexIfNotZero] : items[0]; 

      if (item) { 
       item.click(); 
       return true; 
      } 
     } 
     return false; 

     //alert(rxp); 
    }, [classId, indexIfNotZero], function (result) { 
     console.info(result); 
    }); 
}; 

回答

1

有几件事情,我看到是造成您的问题。

首先,您有variable shadowing这可能会导致问题。您的全局导出命令有2个变量(classIdindexIfNotZero),而您的内部执行命令具有相同的参数名称。

其次,对于自定义命令,this变量实际上是browser。所以,不要做this.browser.execute,你只需拨打this.execute

对于一个完整的工作代码示例,在这里你去:

'use strict'; 

var ClickElementByIndex = function(className, index) { 
    if (!index) { 
    index = 0; 
    } 

    this.execute(function(selector, i) { 
    var $item = $(selector + ':eq(' + i + ')'); 
    if (!!$item) { 
     $item.click(); 
     return true; 
    } 
    return false; 
    }, [className, index], function(result) { 
    console.info(result); 
    }); 
}; 

exports.command = ClickElementByIndex; 

注意,你确实需要的jQuery在你的应用程序的这种全球范围内的工作提供。

+0

我有点想回答这个问题,但是如果index等于0,'!index'条件也会解析为true。这里没有问题,但为了清楚起见'if(index === undefined)'更好。 – koehr