【问题标题】:How to get a value from browser JavaScript global variable using Cucumber\Ruby\PageObject?如何使用 Cucumber\Ruby\PageObject 从浏览器 JavaScript 全局变量中获取值?
【发布时间】:2019-12-07 16:37:19
【问题描述】:

在我的自动测试中,我需要获取 JavaScript 全局变量的值。

例如,从以下 HTML 中获取 global_var 的值:

<!DOCTYPE html>
<html>
<body>
<script>
var global_var = "John Smith"
</script>
<h2>Test JavaScript</h2>

<button type="button"
onclick="document.getElementById('demo').innerHTML = global_var">
Click me to display "global_var" value.</button>

<p id="demo"></p>

</body>
</html> 

这是我尝试过的:

browser.execute_script(“document.global_var”)

【问题讨论】:

  • 你能分享你已经尝试过的吗?
  • 谢谢Ümit,这是我的第一个问题,所以我忽略了添加我尝试过的内容。

标签: javascript ruby automated-tests cucumber pageobjects


【解决方案1】:

更好的是,您可以通过以下方式轻松地将 get_global_variable_value 用于任何全局变量名称:

class TestPage
  include PageObject

  page_url ("<system url that you are testing>")

  def get_global_variable_value var_name
    value = self.browser.execute_script("return window.#{var_name}")
    puts  "Value of #{var_name} is: " + value
  end
end

【讨论】:

    【解决方案2】:

    您可以尝试以下 Ruby\PageObject 代码:

    class TestPage
      include PageObject
    
      page_url ("<system url that you are testing>")
    
      def get_global_variable_value
        value = self.browser.execute_script("return window.global_var")
        puts  "Value of "global_var" is: " + value
      end
    end ```
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-05
      • 2023-01-29
      • 2015-10-08
      相关资源
      最近更新 更多