Selenium Scripting Guide

Prev Next

Overview

Selenium is a suite of tools for testing browser-based interfaces and APIs. You can generate Selenium test scripts by "recording" live interactions with a web page, or by manually writing the scripts in a text editor. This guide is intended to help you use either method to create test scripts for use with your Catchpoint Tests, but it is not an exhaustive guide to Selenium. For complete Selenium documentation, please refer to selenium.dev/documentation/.

Recording a Web Transaction

In order to record a transaction and generate a Selenium Script, you will need to install the Catchpoint Script Recorder browser extension for Chrome.

Once the Catchpoint Script Recorder is installed, follow these steps to record a transaction:

  1. Launch the web browser in which you installed the Catchpoint Script Recorder.
  2. Navigate to your browser extensions, then select the Catchpoint Script Recorder extension. (The exact location of browser extensions will depend on your browser version and display settings.) The Catchpoint Recorder is displayed in a pop-up window.
  3. Input the URL where you want your script process to begin and click Start.
  4. In the main browser window, execute the actions that you want to record for your test script.
  5. Click the Stop button in the Catchpoint Recorder pop-up.
  6. Make any desired edits to the recorded script. (see the rest of this guide and selenium.dev/documentation for more information.)
  7. Copy and paste the finished script into the Script field in your Transaction or API test properties page.

Writing Selenium Scripts

A Selenium script consists of a series of commands. Each command will occupy one line in the script field of the Transaction or API test configuration form.

There are three types of commands in Selenium:

  • Actions are commands that manipulate the state of the application. They do things like click links or select options from menus. Catchpoint does not support all Selenium Actions (see list below for supported Actions).
  • Accessors are commands which examine the state of the application and store the results in variables. For example, an accessor could be used to read the title of the current webpage and store it in a variable called pageTitle. Accessors can also be used to automatically generate Assertions.
  • Assertions are similar to Accessors in that they also examine the state of the application, but Assertions are used to check whether the state of the application conforms to what is expected. For example, an assertion could be used to "make sure this page's title is X" or "verify this checkbox is checked." Your script can then take different actions depending on whether the assertion is confirmed or not.

In addition to commands, Selenium makes use of the following elements to carry out the desired testing logic.

  • Element Locators identify different HTML elements on a webpage so that Selenium commands can refer to them specifically. Many commands require an Element Locator as the "target" attribute. For example, an element locator might identify a specific text input field in a form, or a "Submit" button.
  • Patterns are used for various reasons, such as defining a set of expected values for an input field, or to identify a menu option to select. For example, a pattern could be configured to check that the input in an email address field matches the typical format of an email address. Selenium supports various types of pattern syntaxes, including Regular Expressions.

If an Action fails, or generates an error, the current test is stopped. The open action and the actions that finish with AndWait force the agent to create a new step. Many Actions can be called with the AndWait suffix, e.g. clickAndWait. This suffix tells Catchpoint the action will cause the browser to make a call to the server, and that Catchpoint should create a new step and perform the next action, whether or not a page loads. This could be used to test sites that rely on AJAX, for example.

Supported Actions

Catchpoint's Transaction Test currently supports the following Selenium Actions:

Action Description
addScript(scriptContent,scriptTagId) Loads script content into a new script tag in the web page document. This differs from the runScript command in that runScript adds the script tag to the document of the AUT, not the web page document. scriptContent is the Javascript content of the script to add. scriptTagId (optional) is the id of the new script tag. If specified, and an element with this id already exists, this operation will fail.
addSelection(locator,optionLocator) Add a selection to the set of selected options in a multi-select element using an option locator. Locator is an element locator identifying a multi-select box. optionLocator is an option locator, a label by default; see select action for optionLocator details.
altKeyDown() Press the alt key and hold it down until doAltUp() is called or a new page is loaded.
altKeyUp() Release the alt key.
check(locator) Check a toggle-button (checkbox/radio button). Locator is an element locator.
click(locator) Clicks on a link, button, checkbox or radio button. If the click action causes a new page to load (like a link usually does), call waitForPageToLoad. locator is an element locator.
clickAndWait(locator) Same as click(locator) but telling the browser to wait for the page to load after the click event.
clickAt(locator,coordString) Clicks on a link, button, checkbox or radio button. If the click action causes a new page to load (like a link usually does), call waitForPageToLoad. locator is an element locator. coordString specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator.
clickAtAndWait(locator,coordString) Same as clickAt(locator,coordString) but telling the browser to wait for the page to load after the clickAt event.
controlKeyDown() Press the control key and hold it down until doControlUp() is called or a new page is loaded.
controlKeyUp() Release the control key.
doubleClick(locator) Double clicks on a link, button, checkbox or radio button. If the double click action causes a new page to load (like a link usually does), call waitForPageToLoad. locator is an element locator.
doubleClickAndWait(locator) Same as doubleClick(locator) but telling the browser to wait for the page to load after the double click event.
doubleClickAt(locator,coordString) Doubleclicks on a link, button, checkbox or radio button. If the action causes a new page to load (like a link usually does), call waitForPageToLoad. locator is an element locator. coordString specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator.
doubleClickAtAndWait(locator,coordString) Same as doubleClickAt(locator,coordString) but telling the browser to wait for the page to load after the double click event.
dragAndDrop(locator,movementsString) Drags an element a certain distance and then drops it. locator is an element locator. movementsString is the offset in pixels from the current location to which the element should be moved, e.g., "+70,-300".
dragAndDropToObject
(locatorOfObjectToBeDragged,
locatorOfDragDestinationObject)
Drags an element and drops it on another element. locatorOfObjectToBeDragged is an element to be dragged. locatorOfDragDestinationObject is an element whose location (i.e., whose center-most pixel) will be the point where locatorOfObjectToBeDragged is dropped.
fireEvent(locator,eventName) Explicitly simulate an event, to trigger the corresponding "onevent" handler. locator is an element locator. eventName is the event name, for example, "focus" or "blur".
fireEventAndWait(locator,eventName) Same as fireEvent(locator,eventName) but telling the browser to wait for the page to load after the fireEvent event.
focus(locator) Move the focus to the specified element; for example, if the element is an input field, move the cursor to that field. locator is an element locator.
keyDown(locator,keySequence) Simulates a user pressing a key without releasing it yet. locator is an element locator. keySequence - Either be a string("" followed by the numeric keycode of the key to be pressed, normally the ASCII value of that key), or a single character. For example: "w", "\119".
keyPress(locator,keySequence) Simulates a user pressing and releasing a key. locator is an element locator. keySequence - Either be a string("" followed by the numeric keycode of the key to be pressed, normally the ASCII value of that key), or a single character. For example: "w", "\119".
keyUp(locator,keySequence) Simulates a user releasing a key. locator is an element locator. keySequence - Either be a string("" followed by the numeric keycode of the key to be pressed, normally the ASCII value of that key), or a single character. For example: "w", "\119".
mouseDown(locator) Simulates a user pressing the left mouse button (without releasing it yet) on the specified element. locator is an element locator.
mouseDownAt(locator,coordString) Simulates a user pressing the left mouse button (without releasing it yet) at the specified location. locator is an element locator. coordString specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator.
mouseDownRight(locator) Simulates a user pressing the right mouse button (without releasing it yet) on the specified element. locator is an element locator.
mouseDownRightAt(locator,coordString) Simulates a user pressing the right mouse button (without releasing it yet) at the specified location. locator is an element locator. coordString specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator.
mouseMove(locator) Simulates a user pressing the mouse button, without releasing it yet, on the specified element. locator is an element locator.
mouseMoveAt(locator,coordString) Simulates a user pressing the mouse button, without releasing it yet, on the specified element. locator is an element locator. coordString specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator.
mouseOut(locator) Simulates a user moving the mouse pointer away from the specified element. locator is an element locator.
mouseOver(locator) Simulates a user hovering a mouse over the specified element. locator is an element locator.
mouseUp(locator) Simulates the event that occurs when the user releases the mouse button (i.e., stops holding the button down) on the specified element. locator is an element locator.
mouseUpAt(locator,coordString) Simulates the event that occurs when the user releases the mouse button (i.e., stops holding the button down) at the specified location. locator is an element locator. coordString specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator.
mouseUpRight(locator) Simulates the event that occurs when the user releases the right mouse button (i.e., stops holding the button down) on the specified element. locator is an element locator.
mouseUpRightAt(locator,coordString) Simulates the event that occurs when the user releases the right mouse button (i.e., stops holding the button down) at the specified location. locator is an element locator. coordString specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator.
open(url) Opens an URL in the test frame. This accepts both relative and absolute URLs. The "open" command waits for the page to load before proceeding, ie. the "AndWait" suffix is implicit. Note: The URL must be on the same domain as the runner HTML due to security restrictions in the browser (Same Origin Policy). If you need to open an URL on another domain, use the Selenium Server to start a new browser session on that domain. url is the URL to open; may be relativeor absolute.
pause(waitTime) Wait for the specified amount of time (in milliseconds). waitTime is the amount of time to sleep (in milliseconds).
removeAllSelections(locator) Unselects all of the selected options in a multi-select element. locator is an element locator.
removeSelection(locator,optionLocator) Remove a selection from the set of selected options in a multi-select element using an option locator. locator is an element locator. optionLocator is an option locator (a label by default); see select action for optionLocator details.
runScript(script) Creates a new "script" tag in the body of the current test window, and adds the specified text into the body of the command. Scripts run in this way can often be debugged more easily than scripts executed using Selenium's "getEval" command. Beware that JS exceptions thrown in these script tags aren't managed by Selenium, so you should probably wrap your script in try/catch blocks if there is any chance that the script will throw an exception. script is the JavaScript snippet to run
runScriptAndWait(script) Same as runScript(script) but telling the browser to wait for the page to load after the runScript event.
select(selectLocator,optionLocator) Select an option from a dop-down using an option locator. selectLocator is an element locator identifying a drop-down menu. optionLocator is an option locator (a label by default). Option locators provide different ways to specify options of an HTML select element, for example, to select a specific option or to assert the selected optionsatisfies a specification. There are several forms of Select Option Locator: label=labelPattern: matches options based on their labels, for example, the visible text. this is the default. value=valuePattern: matches options based on their values. id=id: matches options based on their ids. index=index: matches an option based on its index (offset from zero). If no option locator prefix is provided, the default behavior is to match on label.
selectAndWait(selectLocator,optionLocator) Same as select(selectLocator,optionLocator) but telling the browser to wait for the page to load after the select event.
setSpeed(value) Set execution speed (i.e., set the millisecond length of a delay which will follow each selenium operation). By default, there is no such delay, i.e., the delay is 0 milliseconds. value is the number of milliseconds to pause after operation.
shiftKeyDown() Press the shift key and hold down until doShiftUp() is called or a new page is loaded.
shiftKeyUp() Release the shift key.
submit(formLocator) Submit the specified form. This is particularly useful for forms without submit buttons, for example, single input Search forms. formLoactor is an element locator for the form you want to submit.
type(locator,value) Sets the value of an input field, as though you typed it in. Can also be used to set the value of combo boxes, check boxes, etc. In these cases, value should bethe value of the option selected, not the visible test. locator is an element locator. value is the value to type.
typeAndWait(locator,value) Same as type(locator,value) but telling the browser to wait for the page to load after the type event.
typeKeys(locator,value)

Simulates keystroke events on the specified element, as though you typed the value key-by-key. this is a convenience method for calling keyDown, keyUp, keyPress for every character in the specified string; this is useful for dynamic UI widgets (like auto-completing combo boxes) that require explicit key events.

Unlike the simple "type" command, which forces the specified value into the page directly, this command may or may not have any visible effect, even in cases where typing keys would normally have a visible effect. For example, if you use "typeKeys" on a form element, you may or may not see the results of what you typed in the field.

In some cases, you may need to use the simple "type" command to set the value of the field and then the "typeKeys" command to send the keystroke events corresponding to what you just typed.

locator is an element locator. value is the value to type.

typeKeysAndWait(locator,value) Same as typeKeys(locator,value) but telling the browser to wait for the page to load after the typeKeys event.
uncheck(locator) Uncheck a toggle-button (checkbox/radio). locator is an element locator.
waitForPageToLoad(timeout) Waits for a new page to load. You can use this command instead of the "AndWait" suffixes, "clickAndWait", "selectAndWait", "typeAndWait" etc. (which are only available in the JS API). Catchpoint constantly keeps track of new pages loading, and sets a "newPageLoaded" flag when it first notices a page load. Running any other Selenium command after turns the flag to false. Hence, if you want to wait for a page to load, you must wait immediately after a Selenium command that caused a page-load. Timeout is a timeout in milliseconds, after which this command will return with an error.

Selenium Assertions

Assertions are used to check whether the application or part of the application has reached a certain state. There are three versions of each assertion command, each beginning with one of the following:

  • verify commands will check to see if the specified state has been reached and stop the test if so, or allow the test to continue if not.
  • assert commands will check to see if the specified states has been reached and cause the test to fail if the state is not met.
  • waitFor commands will cause the agent to wait for some state to be reached before continuing (which can be useful for testing Ajax applications. A waitFor assertion will succeed immediately if the condition is already true. If the state is not reached before the current timeout setting, the test will fail. (see the setTimeout action in the Selenium Actions section above.

Catchpoint currently supports these Selenium Assertions:

Assertion Description
verifyBodyText(pattern)
assertBodyText(pattern)
waitForBodyText(pattern)
Succeeds when the text in the HTML body of the base page contains a match to the specified pattern.
verifyChecked(locator)
assertChecked(locator)
waitForChecked(locator)
Succeeds when the checkbox or radio button specified by the locator is selected.
verifyElementPresent(locator)
assertElementPresent(locator)
waitForElementPresent(locator)
Succeeds when an element is present on the page which matches the specified locator.
verifyElementNotPresent(locator)
assertElementNotPresent(locator)
waitForElementNotPresent(locator)
Succeeds when no element on the page matches the specified locator.
verifyHtmlSource(pattern)
assertHtmlSource(pattern)
waitForHtmlSource(pattern)
Succeeds when the HTML source for the page contains text matching the specified pattern.
verifyLocation(pattern)
assertLocation(pattern)
waitForLocation(pattern)
Succeeds when the absolute URL of the current page matches the specified pattern
verifySelectedId(locator,pattern)
assertSelectedId(locator,pattern)
waitForSelectedId(locator,pattern)
Succeeds when the ID of the option selected in the specified element matches the pattern.
verifySelectedIndex(locator,pattern)
assertSelectedIndex(locator,pattern)
waitForSelectedIndex(locator,pattern)
Succeeds when the index of the option selected in the specified element matches the pattern.
verifySelectedLabel(locator,pattern)
assertSelectedLabel(locator,pattern)
waitForSelectedLabel(locator,pattern)
Succeeds when the label of the option selected in the specified element matches the pattern.
verifySelectedValue(locator,pattern)
assertSelectedValue(locator,pattern)
waitForSelectedValue(locator,pattern)
Succeeds when the value of the option selected in the specified element matches the pattern.
verifyText(locator,pattern)
assertText(locator,pattern)
waitForText(locator,pattern)
Succeeds if text on the page element specified by the locator matches the specified pattern.
verifyTextPresent(pattern)
assertTextPresent(pattern)
waitForTextPresent(pattern)
Succeeds when any text on the page contains a match to the specified pattern.
verifyTitle(pattern)
assertTitle(pattern)
waitForTitle(pattern)
Succeeds when the page title matches the specified pattern
verifyValue(locator,pattern)
assertValue(locator,pattern)
waitForValue(locator,pattern)
Succeeds when the value contained in the element specified by the locator matches the specified pattern
verifyVisible(locator)
assertVisible(locator)
waitForVisible(locator)
Succeeds when the element specified by the locator is visible

Assertion Examples

// Step - 1
open(http://www.amazon.com)
assertSelectedValue(//*[@id='searchDropdownBox'], search-alias=aps)
verifySelectedValue(//*[@id='searchDropdownBox'], search-alias=aps)
verifySelectedValue(//*[@id='searchDropdownBox'], search-alias=apparel)
assertNotSelectedValue(//*[@id='searchDropdownBox'], search-alias=apparel)
verifyNotSelectedValue(//*[@id='searchDropdownBox'], search-alias=apparel)
verifyNotSelectedValue(//*[@id='searchDropdownBox'], search-alias=aps)
// Step - 1 open(http://www.bing.com)
assertElementPresent(//*[@href='/entertainment?FORM=Z9LH6'])
verifyElementPresent(//*[@href='/entertainment?FORM=Z9LH6'])
verifyElementPresent(//*[@href='/entertainment?FORM=Z9LH9'])
assertElementNotPresent(//*[@href='/entertainment?FORM=Z9LH9'])
verifyElementNotPresent(//*[@href='/entertainment?FORM=Z9LH9'])
verifyElementNotPresent(//*[@href='/entertainment?FORM=Z9LH6'])
// Step - 1 open(http://www.bing.com)
clickandwait(//*[@id='scpt0']/a) waitForElementPresent(//*[@id='sg_root'])
waitForElementPresent(//*[@id='sg_root'])
assertElementPresent(//*[@id='sg_hid'])

Element Locators

Element Locators tell Selenium which HTML element a command refers to. The format of a locator is:

<locatorType>=<argument>

Catchpoint supports the following methods for locating elements:

Method Description
identifier=<value> Select the element with @id attribute matching the specified value. If no match is found, select the first element whose @name attribute matches the value. (This is normally the default; see below.)
id=<value> Select the element with @id attribute matching the specified value.
name=<value> Select the first element with @name attribute matching the specified value.

The value may optionally be followed by one or more element filters, separated from the name by whitespace. If the filterType is not specified, "value" is assumed.

Here are some filter examples:

  • name=flavour value=chocolate
  • dom=document.<expression> Find an element by evaluating the specified string. This allows you to traverse the HTML Document Object Model.
  • dom=document.forms['myForm'].myDropdown
  • dom=document.images[56]
  • xpath=<xpathExpression> *Locate an element using an XPath expression.*
  • xpath=//img[@alt='The image alt text']
  • xpath=//table[@id='table1']//tr[4]/td[2]
  • xpath=//a[contains(@href,'#id1')]
  • xpath=//a[contains(@href,'#id1')]/@class
  • xpath=(//table[@class='stylee'])//th[text()='theHeaderText']/../td
  • xpath=//input[@name='name2' and @value='yes']
  • xpath=//*[text()="right"]
  • link=textPattern *Select the link (anchor) element which contains text matching the specified pattern.*
  • link=The link text
  • ui=uiSpecifierString: Locate an element by resolving the UI specifier string to another locator, and evaluating it. See the Selenium UI-Element Reference for more details.
  • ui=loginPages::loginButton()
  • ui=settingsPages::toggle(label=Hide Email)
  • ui=forumPages::postBody(index=2)//a[2]

Without an explicit locator prefix, Selenium uses the following default strategies:

  • dom, for locators starting with "document."
  • xpath, for locators starting with "//"
  • identifier, otherwise

Please note Selenium CSS element locators are not fully supported in Catchpoint and are converted to XPATH locators when possible.

Regular Expressions

Catchpoint supports Selenium Regular Expression matching implementation, which has 4 types:

  • glob for command-line styled matching (where * = any char, and ? = single char). Default regex match.
  • regexp for case-sensitive regular expressions
  • regexpi for case-insensitive regular expressions
  • exact for exact matching

Regular Expression Example
This example includes all four types of Regular Expression

// Step - 1
open(http://www.catchpoint.com/)
    
// Step - 2
clickAndWait(link=regexp:.*roduc.*)
assertLocation(regexp:(.*)catchpoint(.*)products(.*))  

// Step - 3
clickAndWait(link=regexpi:(.*)about(.*))   assertLocation(exact:http://www.catchpoint.com/about.html)

Catchpoint Custom Actions

The Catchpoint system includes custom actions, in addition to what Selenium provides. They provide features that are not available in Selenium. The format differs slightly from Selenium and does not rely on () brackets. Format is as follows:

Action Name Description Parameter Details
clickMouse Simulates a click event on the currently selected link, button, checkbox or radio button.
dynamicStepOnNewPage 1 Enables the agent to create a new dynamic step when it recognizes that the browser navigated dynamically to a new page. The dynamic navigation could be caused by META refresh tags or JavaScript execution. Set parameter value to 1 to create a single new step for each new page.
setHeader <key><:request?>;<value> Adds or modifies key:value pair in HTTP header. If the <:request> is not specified, the header is added only for the base URL of the step. Examples:
setHeader Debug True
Adds "Debug: True" in the http request headers for the base URL.
setHeader Debug:^http://ads.site.com True
Adds "Debug: True" in the http request headers for any child requests to "http://ads.site.com".
setStepName <name> Names the current step as specified. Step Names can later be used as Filters, Breakdowns, and Dimensions in Charts and Reports. The step name also replaces the URL in the Step section of the Record. <name> is a string. No need for quotation marks.
waitForNoRequest <milliseconds> Tells the agent to wait for the specified number of milliseconds for any additional HTTP requests on the wire/network before continuing to the next action. <milliseconds> is an integer from 1 to 5000
waitForURL <URL> Tells the agent to wait for a response to the request matching the specified URL. <URL> is a string specifying a URL or Regular Expression matching some URL(s)
waitForElementPresent <element> Tells the agent to wait for the specified element to be present on the page before continuing to the next action. <element> is a string matching the name of a page element