This tutorial is for those who need to learn how to create their own extensions for Selenium. The tutorial is aimed at more experienced Selenium users who understand basic JavaScript.When creating a new user extension you will need add your code to the user-extension.js file. You will need to make sure that this file is accessible to all Selenium Derivatives(Selenium IDE,Selenium Core and Selenium Remote Control).
Lets start by breaking down an extension from the user contributed section of extensions from the OpenQA Wiki
The new user extension that you will be creating will be accessed via the Selenium API so the first thing that we need to do is create a new function within the Selenium Object.
The first line of the snippet below shows that the function is part Selenium. The "do" in Selenium.prototype.doWaitForCondition shows that this will be picked up as an action within Selenium.
Selenium.prototype.doWaitForCondition = function(script, timeout) {
if (isNaN(timeout)) {
throw new SeleniumError("Timeout is not a number: " + timeout);
}
testLoop.waitForCondition = function () {
return eval(script);
};
testLoop.waitForConditionStart = new Date().getTime();
testLoop.waitForConditionTimeout = timeout;
testLoop.pollUntilConditionIsTrue = function () {
try {
if (this.waitForCondition()) {
this.waitForCondition = null;
this.waitForConditionStart = null;
this.waitForConditionTimeout = null;
this.continueCommandExecutionWithDelay();
} else {
if (this.waitForConditionTimeout != null) {
var now = new Date();
if ((now - this.waitForConditionStart) > this.waitForConditionTimeout) {
throw new SeleniumError("Timed out after " + this.waitForConditionTimeout + "ms");
}
}
window.setTimeout("testLoop.pollUntilConditionIsTrue()", 10);
}
} catch (e) {
var lastResult = new CommandResult();
lastResult.failed = true;
lastResult.failureMessage = e.message;
this.commandComplete(lastResult);
this.testComplete();
}
};
};
function(script, timeout) means that your new function can handle the 2 arguments that Selenium Actions need.CommandResult().failed and .passed
functions to say if the test has passed or failed. You only need to do this if
you are creating a new function that can influence the Pass/Fail state of the
test.failureMessage that will store a message that will
then be printed to the Selenium derivative that you are using.this.commandComplete(lastResult);. This is also
very useful in the catch of a try...catch to say that the action is finished.this.testComplete(); as the last line of the try...catch block. It will terminate the
action and the test. If you have this and the line is called your test will stop running and it will move onto the next
test in your test suite.If you follow these basic steps you will be able to create your own user extension for Selenium and call your functions just as if they were built in to Selenium!