【问题标题】:How to write a nightwatch custom command using jquery如何使用 jquery 编写守夜人自定义命令
【发布时间】:2016-04-27 20:43:17
【问题描述】:

我有以下用 javascript 为 nightwatch.js 编写的自定义命令。如何将其翻译为使用 jquery?

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);
    });
};

【问题讨论】:

    标签: javascript jquery nightwatch.js


    【解决方案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 才能使其正常工作。

    【讨论】:

    • 回答这个问题我有点吃不消,但是如果 index 也等于 0,!index 条件也会解析为 true。这不是问题,但为了清楚起见if (index === undefined) 更好。
    猜你喜欢
    • 1970-01-01
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多