简体   繁体   English

如何使用 jquery 编写 nightwatch 自定义命令

[英]How to write a nightwatch custom command using jquery

I have the following custom command written in javascript for nightwatch.js.我有以下用 javascript 编写的用于 nightwatch.js 的自定义命令。 How can I translate this to using jquery?如何将其转换为使用 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);
    });
};

There are a few things that I see that are causing your issues.我看到有一些事情导致了您的问题。

First, you have variable shadowing that may cause issues.首先,您有可能导致问题的可变阴影 Your global export command has 2 variables ( classId and indexIfNotZero ) and your internal execute command has the same parameter names.您的全局导出命令有 2 个变量( classIdindexIfNotZero )并且您的内部执行命令具有相同的参数名称。

Second, for custom commands, the this variable is actually the browser .其次,对于自定义命令, this变量实际上是browser So instead of doing this.browser.execute , you need to just call this.execute .因此,您无需执行this.browser.execute ,而只需调用this.execute

As for a complete working code example, here you go:至于完整的工作代码示例,请看这里:

'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;

Note that you do need jQuery available in the global scope of your app for this to work.请注意,您确实需要在应用程序的全局范围内使用 jQuery 才能使其工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM