在selenium中加载一个包含有用测试函数的外部js文件

Load an external js file containing useful test functions in selenium

本文关键字:函数 测试 有用 外部 文件 js 包含 一个 加载 selenium      更新时间:2023-09-26

selenium中的runScript命令非常有用,我使用它来计算表中的值,然后像这样存储值

<tr>
    <td>runScript</td>
    <td>var cumulative = 0.0; $('table.quote-review-group-component').eq(0).find('tr').each( function( i,el ){var singleStackTotal = $(el).find('td').eq(4).html();if( singleStackTotal ){cumulative += parseFloat( singleStackTotal.substring(1) );} }); cumulative = cumulative.toFixed(2)</td>
    <td></td>
</tr>
<tr>
    <td>storeEval</td>
    <td>selenium.browserbot.getUserWindow().cumulative</td>
    <td>cumulative</td>
</tr>
<tr>
    <td>echo</td>
    <td>${cumulative}</td>
    <td></td>
</tr>
<tr>
    <td>verifyEquals</td>
    <td>£${cumulative}</td>
    <td>${total}</td>
</tr>

理想情况下,我希望能够指向外部js文件,而不是将命令中的javascript作为字符串,这样我就可以加载一些测试函数并使用storeEval来获得函数的返回

所以我们有

<tr>
    <td>runExternalScript</td>
    <td>/path/to/external/extra-tests.js</td>
    <td></td>
</tr>
<tr>
    <td>storeEval</td>
    <td>selenium.browserbot.getUserWindow().getCumulative(0)</td>
    <td>cumulative0</td>
</tr>
<tr>
    <td>verifyEquals</td>
    <td>£${cumulative}</td>
    <td>${total}</td>
</tr>

外部脚本看起来像这样

function checkSingleGroupListTotal( index ){
    if ( index == "undefined" ){
        index = 0;
    }
    var cumulative = 0.0; 
    $('table.quote-review-group-component').eq(index).find('tr').each( function( i,el ){
        var singleStackTotal = $(el).find('td').eq(4).html();    
        if( singleStackTotal ){         
            cumulative += parseFloat( singleStackTotal.substring(1) );     
        } 
    }); 
    return cumulative.toFixed(2);
}

考虑一个插件,它添加了一个loadScript动作来检查外部js文件,然后将文件内容传递给runScript来完成这项工作。但是我不想重新发明轮子,我以前从来没有做过插件。

runScript命令只是将包含脚本的<SCRIPT>元素添加到DOM中,并让浏览器运行它。您可以自己做同样的事情,而不是使用内联脚本,使用SRC=属性来告诉浏览器加载什么文件。您可能必须从web服务器加载文件,因为一些浏览器不允许从网络加载的页面访问file: URL。