executeScript不起作用

时间:2016-06-29 12:29:17

标签: javascript protractor angularjs-e2e

我的测试中有一些JS脚本。我不明白为什么,但它现在停止工作。 也许它发生在量角器更新之后(到版本3.3.0)。 也许有人知道会发生什么?

我的脚本:

    PsComponent.prototype.getHighlightedText = function () {
  return browser.executeScript_(function getSelectionText() {
    var text = "";
    if (window.getSelection) {
      text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
      text = document.selection.createRange().text;
    }
    return text;
  });
};

结果:

nothing

    PsComponent.prototype.getCaretPosition = function () {
  return browser.executeScript(function (input) {
    if (document.selection && document.selection.createRange) {
      var range = document.selection.createRange();
      var bookmark = range.getBookmark();
      var caret_pos = bookmark.charCodeAt(2) - 2;
    } else {
      if (input.setSelectionRange){
        caret_pos = input.selectionStart;
      }
    }
    return caret_pos;
  });
};

结果:

- Failed: JavaScript error (WARNING: The server did not provide any stacktrace information)

1 个答案:

答案 0 :(得分:1)

没有直接回答这个问题,但是我们正在使用类似的功能(我想这样的事情自然会出现在任何浏览器测试自动化项目中):

this.getCaretPosition = function (elm) {
    return browser.executeScript(function () {
        var webElement = arguments[0];

        return webElement.value.slice(0, webElement.selectionStart).length;
    }, elm.getWebElement())
};

this.getInputSelection = function (elm) {
    return browser.executeScript(function () {
        var webElement = arguments[0];

        return webElement.value.substring(webElement.selectionStart, webElement.selectionEnd);
    }, elm.getWebElement())
};

用法样本:

expect(helpers.getCaretPosition(amountInput)).toEqual(1);
expect(helpers.getInputSelection(amountInput)).toEqual("-100.00");