How to create custom functions in Selenium IDE?

こ雲淡風輕ζ 提交于 2019-12-05 09:27:31

What you need is a self executing anonymous function:

<tr>
    <td>storeEval</td>
    <td>(function(input) {return input.replace(input, 'bar');})('foo')</td>
    <td>replaceText</td>
</tr>

Note that you can also use your variables as parameters:

<tr>
    <td>store</td>
    <td>'foo'</td>
    <td>searchText</td>
</tr>
<tr>
    <td>storeEval</td>
    <td>(function(input) {return input.replace(input, 'bar');})(${searchText})</td>
    <td>replaceText</td>
</tr>

I test above,but I got a error "[error] Threw an exception: missing ) after argument list" so,I change "${searchText}" to "storedVars['searchText']", it's ok :)

ps:JavaScript can be used with two types of Selenese parameters: script and non-script (usually expressions). In most cases, you’ll want to access and/or manipulate a test case variable inside the JavaScript snippet used as a Selenese parameter. All variables created in your test case are stored in a JavaScript associative array. An associative array has string indexes rather than sequential numeric indexes. The associative array containing your test case’s variables is named storedVars. Whenever you wish to access or manipulate a variable within a JavaScript snippet, you must refer to it as storedVars[‘yourVariableName’].

http://www.seleniumhq.org/docs/02_selenium_ide.jsp#store-commands-and-selenium-variables

Katranci's answer was really useful, but once I added in for loops the variables would lose scope. I wound up using Katranci's solution inside window.eval().

window.eval('(function() { var trs = document.querySelectorAll(".my-list table tbody tr"); for (var x in trs) { var trc = trs[x].childNodes; for (var y in trc) { var html = trc[y].innerHTML; if (typeof html != "undefined" && html.match(/Selenium Testing/)) { return trs[x].className.replace(" lastrow", "");     }   } } } )();');

In this situation, I was creating test entries prefixed with 'Selenium Testing' and am using this code to identify those for subsequent test cases. This happens to be a page without jquery.

It is possible to define a function and reuse it elsewhere:

<tr>
    <td>storeEval</td>
    <td>(function(){return function(min,max){return Math.floor(Math.random()*(max-min)) + min;} })()</td>
    <td>randomIntInRange</td>
</tr>
<tr>
    <td>storeEval</td>
    <td>(function(){return storedVars['randomIntInRange'](10000,99999) +'-'+ storedVars['randomIntInRange'](1000,9999) })()</td>
    <td>randomZip</td>
</tr>
<tr>
    <td>echo</td>
    <td>${randomZip}</td>
    <td></td>
</tr>
...
[info] echo: 92105-3139

This works in Selenium IDE 2.9.0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!