javascript - 使用 Java Selenium JavascriptExecutor 访问 AngularJS 变量

标签 javascript java angularjs selenium

这是一个带有 AngularJS ng-click 属性的 div,该属性在单击 div 时设置一个变量。

<div id="id"
     ng-click="foo.bar = true;">
     Set bar variable on foo object to true
</div>

下面是一些使用 Selenium 来点击 div 元素的 Java 代码。

By upload = By.id("id");
driver.findElement(uploadCensus).click();

当我运行 Java 代码时,AngularJS 永远挂起。我认为单击 div 时未设置 foo.bar,所以这里有一些直接设置变量的代码。

By upload = By.id("id");
((JavascriptExecutor) driver)
    .executeScript("foo.bar = true;",   
    driver.findElement(upload));

堆栈跟踪

unknown error: foo is not defined (Session info: chrome=56.0.2924.87) (Driver info: chromedriver=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 51 milliseconds Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58' System info: host: 'WV-VC104-027', ip: '{ip}', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_151' Driver info: org.openqa.selenium.chrome.ChromeDriver Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed), userDataDir=C:\Users{user}\AppData\Local\Temp\scoped_dir5600_4225}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=56.0.2924.87, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}] Session ID: a7734312eff62fe452a53895b221a58d

当我尝试设置 foo.bar 时,我无法获得对变量的引用,因为它不是全局定义的,而是埋在 AngularJS 源代码中的某个地方。我试图缩小索引并寻找变量,但我似乎找不到它。我想通过 JavascriptExecutor 手动设置 foo.bar 变量,但无法获得对该变量的引用。我将如何找到然后设置变量?

如果这似乎是触发此 ng-click 的错误方式,我愿意接受想法。我确信 Protractor 有办法处理这个问题,但是这个 AngularJS 应用程序部署在企业环境中,并且几个月来一直试图让业务方批准该技术。我被 Selenium 困住了。帮助...

最佳答案

直接回答您的问题 [不要将其用于您的情况:)]

Angular 有独立的变量范围。所以你需要获取范围并在其中设置变量。

angular.element("#id").scope().foo.bar = true;

但不要将它用于您的情况。当您在系统级别测试应用程序时,您必须像用户一样测试它们。

推荐答案:WAITING java 中的 Angular 可测试性

无论 Protractor 能处理什么,您的 Java 测试也能处理。两者都是 Selenium 绑定(bind)的包装器。最终,所有 selenese 代码都在您测试的同一浏览器中执行。

waitForAngularMethod 是您在测试中最不可避免缺少的方法。好消息是您可以在 expilcit wait 中使用 JavaScriptExecutor 执行相同类型的 javascript。

如果您是 javascript 爱好者,可以引用 waitForangular Protractor 中的方法实现。这只是一个简单的验证检查并使用回调等待。

用于为 waitforangular 创建预期条件的 java 代码

String waitForAngularJs ="Your javascript goes here"; // as it is lengthy read it from file and store here.
ExpectedCondition<Boolean> waitForAngular= new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver driver) {
                return ((JavascriptExecutor) driver).executeAsyncScript(waitForAngularJs).equals(true);
            }
};

 WebDriverWait wait = new WebDriverWait(driver, 60);
 wait.until(waitForAngular);

等待 angular Javascript(为您的 Java 执行而修改。但我没有检查它):

该方法需要两个属性,root locator hook 和回调。我已将回调设置为一个简单的函数 return true 并与 [ng-app] 的根定位器 Hook 。

var testCallback = function() {
  return true;
 };

    // Wait for angular1 testability first and run waitForAngular2 as a callback
    var waitForAngular1 = function(callback) {

      if (window.angular) {
        var hooks = window.angular.element('[ng-app]');
        if (!hooks){
          callback();  // not an angular1 app
        }
        else{
          if (hooks.$$testability) {
            hooks.$$testability.whenStable(callback);
          } else if (hooks.$injector) {
            hooks.$injector.get('$browser')
                .notifyWhenNoOutstandingRequests(callback);
          } else if (!rootSelector) {
            throw new Error(
                'Could not automatically find injector on page: "' +
                window.location.toString() + '".  Consider using config.rootEl');
          } else {
            throw new Error(
                'root element (' + rootSelector + ') has no injector.' +
                ' this may mean it is not inside ng-app.');
          }
        }
      }
      else {callback();}  // not an angular1 app
    };

    // Wait for Angular2 testability and then run test callback
    var waitForAngular2 = function() {
      if (window.getAngularTestability) {
        if (rootSelector) {
          var testability = null;
          var el = document.querySelector(rootSelector);
          try{
            testability = window.getAngularTestability(el);
          }
          catch(e){}
          if (testability) {
            testability.whenStable(testCallback);
            return;
          }
        }

        // Didn't specify root element or testability could not be found
        // by rootSelector. This may happen in a hybrid app, which could have
        // more than one root.
        var testabilities = window.getAllAngularTestabilities();
        var count = testabilities.length;

        // No angular2 testability, this happens when
        // going to a hybrid page and going back to a pure angular1 page
        if (count === 0) {
          testCallback();
          return;
        }

        var decrement = function() {
          count--;
          if (count === 0) {
            testCallback();
          }
        };
        testabilities.forEach(function(testability) {
          testability.whenStable(decrement);
        });

      }
      else {testCallback();}  // not an angular2 app
    };

    if (!(window.angular) && !(window.getAngularTestability)) {
      // no testability hook
      throw new Error(
          'both angularJS testability and angular testability are undefined.' +
          '  This could be either ' +
          'because this is a non-angular page or because your test involves ' +
          'client-side navigation, which can interfere with Protractor\'s ' +
          'bootstrapping.  See http://git.io/v4gXM for details');
    } else {waitForAngular1(waitForAngular2);}  // Wait for angular1 and angular2
// Testability hooks sequentially

为什么我们需要等待背后的 Angular 和逻辑

为什么我们需要这个,因为 Angular 使用 html 模板、双向数据绑定(bind)、ajax 请求和路由。所以在页面导航之后,我们必须等待所有这些操作(请求和 promise )完成。否则 html 将不会像您的情况那样按预期响应。

检查 Angular 可测试性

即检查 Angular 可测试性。为此angular本身提供了一种方法。

根据元素进行检查,

 window.getAngularTestability(el).whenStable(callback); //Here el is element to be valiated.

检查所有可测试性,

 window.getAllAngularTestabilities();
   testabilities.forEach(function(testability) {
        testability.whenStable(callback);
});

等待所有http挂起的请求完成

在检查 Angular 可测试性之前,我们可以确保没有 http 请求挂起,并带有以下行。

angular.element(document).injector().get('$http').pendingRequest.length

关于javascript - 使用 Java Selenium JavascriptExecutor 访问 AngularJS 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52908425/

相关文章:

javascript - Bootstrap 4 崩溃不适用于 jquery 缩小版

java - 如何在 MorphiaQuery 中检索 @Reference 字段/哪个是最好的 @Reference 或 @Embedded 和 SubQuery

java - 在 Java 中比较二维数组和一维数组

javascript - Angularjs blueimp fileUpload手动触发提交

javascript - Angular ng ui grid 网格导致网页水平滚动

javascript - 缩小 JS 时 Angular 模板返回 404

javascript - ES6 js 关键字作为参数的精确行为

javascript - Internet Explorer 不解析 javascript 方法

javascript - node.js超时重新启动api调用

java - 无法再编译