Selenium-webdriver系列教程(十)————使用jquery輔助進行測試


Jquery是當下比較流行的1個js框架,通過使用webdriver的execute_script方法,我們可以將jquery庫結合到自動化測試中去。

結合jquery進行自動化測試的思想是這樣的:首先將jquery的源碼讀到1個string中去,然后使用execute_script執行該string。執行完畢后我們就可以通過execute_script方法來調用jquery庫了。

下面的html代碼中有一個隱藏的div,當鼠標移動到(mouseover)頁面上名為Mouse Over Here的鏈接時,隱藏的div將會顯示出來。

<html>
    <head>
        <title>FireEvent</title>
        <style>
            .mo {color: blue;}
            .tips {display:none;border: 1px solid #ccc; background-color:#EFEFEF;width: 100px;height:100px}
        </style>
        <script>
            function show_tips(){
                document.getElementById("t").style.display = "block";
            }
            function hide_tips(){
                document.getElementById("t").style.display = "none";
            }
        </script>
    </head>
    <body>
        <a class = "mo" href = "#" onmouseover = "show_tips()" onmouseout = "hide_tips()">Mouse Over Here</a>
        <div id = "t" class = "tips">This is the tips of link</div>
    </body>
</html>

下面的代碼使用jquery的庫函數實現了不去觸發Mouse Over Here鏈接而直接顯示隱藏div的效果(僅在ruby1.9.2下測試過,ruby1.8x應該都不支持)

jquery_helper.rb

#encoding: utf-8
module JqueryHelper
    def load_jquery dr,jquery_path
        jq = read_jquery(jquery_path)
        jq.force_encoding('utf-8')
        dr.execute_script jq
    end

    def read_jquery(jquery_path)
        js = ''
        File.open(File.expand_path(jquery_path), 'r') do |f|
            js = f.read
        end
        js
    end
end

fire_event.rb

require 'rubygems'
require 'selenium-webdriver'
require './jquery_helper'
include JqueryHelper
dr = Selenium::WebDriver.for :firefox
select_file = 'file:///'.concat File.expand_path(File.join(File.dirname(__FILE__), 'fire_event.html'))
dr.navigate.to select_file

jquery_path = './jquery-1.6.4.min.js'
load_jquery dr, jquery_path
jq = <<JQ
    $("#t").show();
JQ

dr.execute_script jq

使用jquery來輔助測試實用性應該不是很強,不過有些時候可以使用jquery方法來獲得dom節點的css屬性,從而達到簡化腳本的目的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM