How to write a nightwatch custom command using jquery

纵饮孤独 提交于 2019-12-01 08:07:31

问题


I have the following custom command written in javascript for nightwatch.js. How can I translate this to using 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);
    });
};

回答1:


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.

Second, for custom commands, the this variable is actually the browser. So instead of doing this.browser.execute, you need to just call 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.



来源:https://stackoverflow.com/questions/36830349/how-to-write-a-nightwatch-custom-command-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!