Selenium Reference

A command is what tells Selenium what to do. Selenium commands come in two 'flavors', Actions and Assertions. Each command call is one line in the test table of the form:

command target value

Actions are commands that generally manipulate the state of the application. They do things like "click this link" and "select that option". If an Action fails, or has an error, the execution of the current test is stopped.

Checks verify the state of the application conforms to what is expected. Examples include "make sure the page title is X" and "check that this checkbox is checked". It is possible to tell Selenium to stop the test when an Assertion fails, or to simply record the failure and continue.

Element Locators tell Selenium which HTML element a command refers to. Many commands require an Element Locator as the "target" attribute. Examples of Element Locators include "elementId" and "document.forms[0].element". These are described more clearly in the next section.

Element Locators

Element Locators allow Selenium to identify which HTML element a command refers to. There are several forms of Element Locators.

id
locates an element based on the id or name attribute of the element. If an element with a matching id is found, it is chosen.
  • id=TheElementId
name
locates an element based on the name attribute of the element. The first element with a matching name is chosen.
  • name=TheElementName
identifier
locates an element based on the id or name attribute of the element. If an element with a matching id is found, it is chosen. Otherwise, the first element with a matching name is chosen.
  • name=TheElementName
dom
finds an element using the built-in DOM traversal syntax of HTML. DOM Traversal locators must begin with "document.".
  • dom=document.forms['myForm'].myDropdown
  • dom=document.images[56]
xpath
locates an element using a defined XPath expression. XPath locators must begin with "//".
  • xpath=//img[@alt='The image alt text']
  • xpath=//table[@id='table1']//tr[4]/td[2]
link
finds a link with the specified text.
  • link=The link text

Without a locator prefix, a default set of locators will be used. The default set of locators is:

  1. identifier
  2. dom
  3. xpath

Select Option Specifiers

Select Option Specifiers provide different ways of specifying options of an HTML Select element (e.g. for selecting a specific option, or for asserting that the selected option satisfies a specification). There are several forms of Select Option Specifier.

label
matches options based on their labels, i.e. the visible text. Does glob matching so that, for example, "fo*r" will match <option>foobar</option>.
  • label=TheLabel
value
matches options based on their values. Does glob matching so that, for example, "fo*r" will match <option value="foobar">Some option</option>.
  • value=TheValue
id
matches options based on their ids. Does glob matching so that, for example, "opt*1" will match <option id="option1" value="foobar">Some option</option>.
  • id=option1
index
matches an option based on its index (offset from zero).
  • index=2

Without a prefix, the default is to only match on labels.

Selenium Actions

Actions tell Selenium to do something in the application. They generally represent something a user would do.

Many Actions can be called with the "AndWait" suffix. This suffix tells Selenium that the action will cause the browser to make a call to the server, and that Selenium should wait for a new page to load. The exceptions to this pattern are the "open" and "click" actions, which will both wait for a page to load by default.

open

Opens a URL in the test frame. This accepts both relative and absolute URLs.

Note: The URL must be on the same site as Selenium due to security restrictions in the browser (Cross Site Scripting).

target: The URL to open.

value: ignored

examples:

open /mypage  
open http://localhost/  
click (clickAndWait)

Clicks on a link, button, checkbox or radio button. If the click action causes a new page to load (like a link usually does), use "clickAndWait".

target: The id of the element that should be clicked.

value: ignored

examples:

click aCheckbox  
clickAndWait submitButton  
clickAndWait anyLink  
note:
Selenium will always automatically click on a popup dialog raised by the alert() or confirm() methods. (The exception is those raised during 'onload', which are not yet handled by Selenium). You must use [verify|assert]Alert or [verify|assert]Confirmation to tell Selenium that you expect the popup dialog. You may use chooseCancelOnNextConfirmation to click 'cancel' on the next confirmation dialog instead of clicking 'OK'.
type (typeAndWait)

Types (enters) text into an input field. This works for text fields, combo boxes, check boxes, etc.

target: The id of the element where the text should be typed.

value: The text that will be typed, or the value of the option selected (not the visible text).

examples:

type nameField John Smith
typeAndWait textBoxThatSubmitsOnChange newValue
select (selectAndWait)

Select an option from a drop-down, based on a Select Option Specifier.

target: An Element Locator specifying an HTML Select element.

value: An Option Specifier. If more than one option matches (e.g. due to the use of globs like "f*b*", or due to more than one option having the same label or value), then the first option that matches is selected.

examples:

select dropDown Australian Dollars
select dropDown index=0
selectAndWait currencySelector value=AUD
selectAndWait currencySelector label=Aus*lian D*rs
selectWindow

Selects a popup window. Once a popup window has been selected, all commands go to that window. To select the main window again, use "null" as the target.

target: The id of the window to select.

value: ignored

examples:

selectWindow myPopupWindow  
selectWindow null  
pause

Pauses the execution of the test script for a specified amount of time. This is useful for debugging a script or pausing to wait for some server side action.

target: The number of milliseconds to pause.

value: ignored

examples:

pause 5000  
pause 2000  
waitForValue

Waits for a specified input (e.g. a hidden field) to have a specified value. Will succeed immediately if the input already has the value. Is implemented by polling for the value. Warning: can block indefinitely if the input never has the specified value.

target: The input field.

value: The value the input field must have before continuing.

example:

waitForValue finishIndication isfinished
goBack

Simulates the user clicking the "back" button on their browser.

target: ignored

value: ignored

examples:

goBack    
close

Simulates the user clicking the "close" button in the titlebar of a popup window.

target: ignored

value: ignored

examples:

close    
pause

Pauses the execution of the test script for a specified amount of time. This is useful for debugging a script or pausing to wait for some server side action.

target: The number of milliseconds to pause.

value: ignored

examples:

pause 5000  
pause 2000  

store

Stores the value of a parameter into a variable

target: The value to store. This can be constructed using either variable substitution or
javascript evaluation, as detailed in 'Parameter construction and Variables' (below).

value: Name of the variable to store the value into.

examples:

store Mr John Smith fullname
store ${title} ${firstname} ${surname} fullname
store javascript{Math.round(Math.PI * 100) / 100} PI

storeValue

Stores the value of an input field into a variable.

target: The id of the input field.

value: Name of the variable to store the field value into.

examples:

storeValue userName userID
type userName ${userID}

storeText

Stores the text of an element into a variable.

target: The id of the element.

value: Name of the variable to store the element text into.

examples:

storeText currentDate expectedStartDate
verifyValue startDate ${expectedStartDate}

Selenium Checks

Checks are used to verify the state of the application. They can be used to check the value of a form field, the presense of some text, or the URL of the current page.

All Selenium Checks can be used in 2 modes, "assert" and "verify". These behave identically, except that when an "assert" check fails, the test is aborted. When a "verify" check fails, the test will continue execution. This allows a single "assert" to ensure that the application is on the correct page, followed by a bunch of "verify" checks to test form field values, labels, etc.

verifyLocation / assertLocation

Verifies the location of the current page being tested.

target: The expected relative location of the page.

value: ignored

examples:

verifyLocation /mypage  
assertLocation /mypage  
verifyTitle / assertTitle

Verifies the title of the current page.

target: The expected page title.

value: ignored

examples:

verifyTitle My Page  
assertTitle My Page  
verifyValue / assertValue

Verifies the value of an input field (or anything else with a value parameter). For checkbox/radio elements, the value will be "on" or "off" depending on whether the element is checked or not.

target: The id of the element to verify.

value: The expected value.

examples:

verifyValue nameField John Smith
assertValue document.forms[2].nameField John Smith
verifySelected / assertSelected

Verifies that the selected option of a drop-down satisfies a specified Select Option Specifier.

target: Locates the drop-down to verify.

value: A Select Option Specifier that the selected option is expected to satisfy.

examples:

verifySelected dropdown2 John Smith
verifySelected dropdown2 value=js*123
assertSelected document.forms[2].dropDown label=J* Smith
assertSelected document.forms[2].dropDown index=0
verifySelectOptions / assertSelectOptions

Verifies the labels of all options in a drop-down against a comma-separated list. Commas in an expected option can be escaped as ",".

target: Locates the drop-down to verify.

value: A comma-separated list of option labels.

examples:

verifySelectOptions dropdown2 John Smith,Dave Bird
assertSelectOptions document.forms[2].dropDown Smith\, J,Bird\, D
verifyText / assertText

Verifies the text of an element. This works for any element that contains text. This command uses either the textContent (Mozilla-like browsers) or the innerText (IE-like browsers) of the element, which is the rendered text shown to the user.

target: The id of the element to verify.

value: The expected text.

examples:

verifyText statusMessage Successful
assertText //div[@id='foo']//h1 Successful
verifyAttribute / assertAttribute

Verifies the value of an element attribute. An attribute is identified using the syntax <element-locator>@<attribute-name>. This works for all types of element locators.

target: A locator string of the format <element-locator>@<attribute-name>

value: The expected attribute value.

examples:

verifyAttribute txt1@class bigAndBold
assertAttribute document.images[0]@alt alt-text
verifyAttribute //img[@id='foo']/@alt alt-text
verifyTextPresent / assertTextPresent

Verifies that the specified text appears somewhere on the rendered page shown to the user.

target: The text that should be present.

value: ignored

examples:

verifyTextPresent You are now logged in.  
assertTextPresent You are now logged in.  
verifyTextNotPresent / assertTextNotPresent

Verifies that the specified text does not appears anywhere on the rendered page.

target: The text that should not be present.

value: ignored

verifyElementPresent / assertElementPresent

Verifies that the specified element is somewhere on the page.

target: The element that should be present.

value: ignored

examples:

verifyElementPresent submitButton  
assertElementPresent //img[@alt='foo']  
verifyElementNotPresent / assertElementNotPresent

Verifies that the specified element is not on the page.

target: The element that should not be present.

value: ignored

examples:

verifyElementNotPresent cancelButton  
assertElementNotPresent cancelButton  
verifyTable / assertTable

Verifies the text in a cell of a table. The correct syntax of the target is tableName.row.column, where row and column start at 0.

target: The table, row, and column specified as table.row.col.

value: The expected value of the cell.

examples:

verifyTable myTable.1.6 Submitted
assertTable results.0.2 13
verifyVisible / assertVisible

Verifies that the specified element is both present and visible. An element can be rendered invisible by setting the CSS "visibility" property to "hidden", or the "display" property to "none", either for the element itself or one if its ancestors.

target: The element that should be visible.

value: ignored

examples:

verifyVisible postcode  
assertVisible postcode  
verifyNotVisible / assertNotVisible

Verifies that the specified element is not visible. Elements that are simply not present are also considered invisible.

target: The element that should not be visible.

value: ignored

examples:

verifyNotVisible postcode  
assertNotVisible postcode  
verifyEditable / assertEditable

Verifies that the specified element is editable, ie. it's an input element, and hasn't been disabled.

target: The element that should be editable.

value: ignored

examples:

verifyEditable shape  
assertEditable colour  
verifyNotEditable / assertNotEditable

Verifies that the specified element is NOT editable, ie. it's NOT an input element, or has been disabled.

target: The element that should be read-only.

value: ignored

examples:

verifyNotEditable creditLimit  
assertNotEditable userName  
verifyAlert / assertAlert

Verifies that a javascript alert was generated and that the text of the alert was as specified. Alerts must be verified in the same order that they were generated.

Verifying an alert has the same effect as manually clicking OK. If an alert is generated but you do not verify it, the next Selenium action will fail.

NOTE: under Selenium, javascript alerts will NOT pop up a visible alert dialog.

NOTE: Selenium does NOT support javascript alerts that are generated in a page's onload() event handler. In this case a visible dialog WILL be generated and Selenium will hang until you manually click OK.

target: The expected text of the alert.

value: ignored

examples:

verifyAlert Invalid Phone Number  
assertAlert Invalid Phone Number  
verifyConfirmation / assertConfirmation

Verifies that a javascript confirmation dialog was generated and that the text of the dialog was as specified. Confirm dialogs must be verified in the same order that they were generated.

By default, the confirm function will return true, having the same effect as manually clicking OK. This can be changed by prior execution of the chooseCancelOnNextConfirmation command (see below). If an confirmation is generated but you do not verify it, the next Selenium action will fail.

NOTE: under Selenium, javascript confirmations will NOT pop up a visible dialog.

NOTE: Selenium does NOT support javascript confirmations that are generated in a page's onload() event handler. In this case a visible dialog WILL be generated and Selenium will hang until you manually click OK.

target: The expected text of the alert.

value: ignored

examples:

verifyConfirmation Invalid Phone Number  
assertAlert Invalid Phone Number  
chooseCancelOnNextConfirmation

Instructs Selenium to click Cancel on the next javascript confirmation dialog to be raised. By default, the confirm function will return true, having the same effect as manually clicking OK. After running this command, the next confirmation will behave as if the user had clicked Cancel.

target: ignored

value: ignored

examples:

chooseCancelOnNextConfirmation    

Parameter construction and Variables

All Selenium command parameters can be constructed using both simple variable substitution as well as full javascript. Both of these mechanisms can access previously stored variables, but do so using different syntax.

Stored Variables

The commands store, storeValue and storeText can be used to store a variable value for later access. Internally, these variables are stored in a map called "storedVars", with values keyed by the variable name. These commands are documented in the command reference.

Variable substitution

Variable substitution provides a simple way to include a previously stored variable in a command parameter. This is a simple mechanism, by which the variable to substitute is indicated by ${variableName}. Multiple variables can be substituted, and intermixed with static text.

Example:
store Mr title
storeValue nameField surname
store ${title} ${surname} fullname
type textElement Full name is: ${fullname}

Javascript evaluation

Javascript evaluation provides the full power of javascript in constructing a command parameter. To use this mechanism, the entire parameter value must be prefixed by 'javascript{' with a trailing '}'. The text inside the braces is evaluated as a javascript expression, and can access previously stored variables using the storedVars map detailed above. Note that variable substitution cannot be combined with javascript evaluation.

Example:
store javascript{'merchant' + (new Date()).getTime()} merchantId
type textElement javascript{storedVars['merchantId'].toUpperCase()}

Extending Selenium

It can be quite simple to extend Selenium, adding your own actions, checks and locator-strategies. This is done with javascript by adding methods to the Selenium object prototype, and the PageBot object prototype. On startup, Selenium will automatically look through methods on these prototypes, using name patterns to recognise which ones are actions, checks and locators.

The following examples try to give an indication of how Selenium can be extended with javascript.

Actions

All doFoo methods on the Selenium prototype are added as actions. For each action foo there is also an action fooAndWait registered. An action method can take up to 2 parameters, which will be passed the second and third column values in the test.

Example: Add a "typeRepeated" action to Selenium, which types the text twice into a text box.

Selenium.prototype.doTypeRepeated = function(locator, text) {
    // All locator-strategies are automatically handled by "findElement"
    var element = this.page().findElement(locator);

    // Create the text to type
    var valueToType = text + text;

    // Replace the element text with the new text
    this.page().replaceText(element, valueToType);
};
Checks

All assertFoo methods on the Selenium prototype are added as checks. For each check foo there is an assertFoo and verifyFoo registered. An assert method can take up to 2 parameters, which will be passed the second and third column values in the test.

Example: Add a valueRepeated check, that makes sure that the element value consists of the supplied text repeated. The 2 commands that would be available in tests would be assertValueRepeated and verifyValueRepeated.

Selenium.prototype.assertValueRepeated = function(locator, text) {
    // All locator-strategies are automatically handled by "findElement"
    var element = this.page().findElement(locator);

    // Create the text to verify
    var expectedValue = text + text;

    // Get the actual element value
    var actualValue = element.value;

    // Make sure the actual value matches the expected
    this.assertMatches(expectedValue, actualValue);
};
Locator Strategies

All locateElementByFoo methods on the PageBot prototype are added as locator-strategies. A locator strategy takes 2 parameters, the first being the locator string (minus the prefix), and the second being the document in which to search.

Example: Add a "valuerepeated=" locator, that finds the first element a value attribute equal to the the supplied value repeated.

// The "inDocument" is a the document you are searching.
PageBot.prototype.locateElementByValueRepeated = function(text, inDocument) {
    // Create the text to search for
    var expectedValue = text + text;

    // Loop through all elements, looking for ones that have a value === our expected value
    var allElements = inDocument.getElementsByTagName("*");
    for (var i = 0; i < allElements.length; i++) {
        var testElement = allElements[i];
        if (testElement.value && testElement.value === expectedValue) {
            return testElement;
        }
    }
    return null;
};
user-extensions.js

By default, Selenium looks for a file called "user-extensions.js", and loads and javascript code found in that file. This file provides a convenient location for adding features to Selenium, without needing to modify the core Selenium sources.

In the standard distibution, this file does not exist. Users can create this file and place their extension code in this common location, removing the need to modify the Selenium sources, and hopefully assisting with the upgrade process.


: