2016-04-25 29 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