Class Protractor

Creates a new WebDriver client, which provides control over a browser.

Every WebDriver command returns a {@code webdriver.promise.Promise} that represents the result of that command. Callbacks may be registered on this object to manipulate the command result or catch an expected error. Any commands scheduled with a callback are considered sub-commands and will execute before the next command in the current frame. For example:

var message = []; driver.call(message.push, message, 'a').then(function() { driver.call(message.push, message, 'b'); }); driver.call(message.push, message, 'c'); driver.call(function() { alert('message is abc? ' + (message.join('') == 'abc')); });

Hierarchy

Index

Constructor methods

Properties

Methods

Constructor methods

constructor(webdriver: WebDriver, opt_baseUrl?: string, opt_rootElement?: string): Protractor

constructor

Parameters

  • webdriver: WebDriver
  • opt_baseUrl?: string optional

    A base URL to run get requests against.

  • opt_rootElement?: string optional

    Selector element that has an ng-app in scope.

Returns

Protractor

Properties

public baseUrl: string

All get methods will be resolved against this base URL. Relative URLs are = resolved the way anchor tags resolve.

type

{string}

public driver: WebDriver

The wrapped webdriver instance. Use this to interact with pages that do not contain Angular (such as a log-in screen).

type

{webdriver.WebDriver}

public ignoreSynchronization: boolean

If true, Protractor will not attempt to synchronize with the page before performing actions. This can be harmful because Protractor will not wait until $timeouts and $http calls have been processed, which can cause tests to become flaky. This should be used only when necessary, such as when a page continuously polls an API using $timeout.

type

{boolean}

public params: any

An object that holds custom test parameters.

type

{Object}

public rootEl: string

The css selector for an element on which to find Angular. This is usually 'body' but if your ng-app is on a subsection of the page it may be a subelement.

type

{string}

Methods

public $(cssLocator: string): ElementFinder

Helper function for finding elements by css.

type

{function(string): ElementFinder}

Parameters

  • cssLocator: string

Returns

ElementFinder

public $$(cssLocator: string): ElementArrayFinder

Helper function for finding arrays of elements by css.

type

{function(string): ElementArrayFinder}

Parameters

  • cssLocator: string

Returns

ElementArrayFinder

public actions(): ActionSequence

Creates a new action sequence using this driver. The sequence will not be scheduled for execution until {@link webdriver.ActionSequence#perform} is called. Example:


  driver.actions().
      mouseDown(element1).
      mouseMove(element2).
      mouseUp().
      perform();

Returns

ActionSequence

A new action sequence for this instance.

public addMockModule(name: string, script: string)

Add a module to load before Angular whenever Protractor.get is called. Modules will be registered after existing modules already on the page, so any module registered here will override preexisting modules with the same name.

Parameters

  • name: string

    The name of the module to load or override.

  • script: string

    The JavaScript to load the module.

public addMockModule(name: string, script: any)

Parameters

  • name: string
  • script: any

public call(fn: any, opt_scope?: any, var_args?: Array<any>): Promise

Schedules a command to execute a custom function.

Parameters

  • fn: any

    The function to execute.

  • opt_scope?: any optional

    The object in whose scope to execute the function.

  • var_args?: Array<any> optional

    Any arguments to pass to the function.

Returns

Promise

A promise that will be resolved with the function's result.

public clearMockModules()

Clear the list of registered mock modules.

public close(): Promise

Schedules a command to close the current window.

Returns

Promise

A promise that will be resolved when this command has completed.

public controlFlow(): ControlFlow

Returns

ControlFlow

The control flow used by this instance.

public debugger()

Pauses the test and injects some helper functions into the browser, so that debugging may be done in the browser console.

This should be used under node in debug mode, i.e. with protractor debug

While in the debugger, commands can be scheduled through webdriver by entering the repl: debug> repl Press Ctrl + C to leave rdebug repl

ptor.findElement(protractor.By.input('user').sendKeys('Laura')); ptor.debugger(); debug> c

This will run the sendKeys command as the next task, then re-enter the debugger.

public element(locator: Locator): ElementFinder

Helper function for finding elements.

type

{function(webdriver.Locator): ElementFinder}

Parameters

Returns

ElementFinder

public executeAsyncScript(script: string, var_args?: Array<any>): Promise

Schedules a command to execute asynchronous JavaScript in the context of the currently selected frame or window. The script fragment will be executed as the body of an anonymous function. If the script is provided as a function object, that function will be converted to a string for injection into the target window.

Any arguments provided in addition to the script will be included as script arguments and may be referenced using the {@code arguments} object. Arguments may be a boolean, number, string, or {@code webdriver.WebElement}. Arrays and objects may also be used as script arguments as long as each item adheres to the types previously mentioned.

Unlike executing synchronous JavaScript with {@code webdriver.WebDriver.prototype.executeScript}, scripts executed with this function must explicitly signal they are finished by invoking the provided callback. This callback will always be injected into the executed function as the last argument, and thus may be referenced with {@code arguments[arguments.length - 1]}. The following steps will be taken for resolving this functions return value against the first argument to the script's callback function:

  • For a HTML element, the value will resolve to a {@code webdriver.WebElement}
  • Null and undefined return values will resolve to null
  • Booleans, numbers, and strings will resolve as is
  • Functions will resolve to their string representation
  • For arrays and objects, each member item will be converted according to the rules above

Example #1: Performing a sleep that is synchronized with the currently selected window:

var start = new Date().getTime();
driver.executeAsyncScript(
    'window.setTimeout(arguments[arguments.length - 1], 500);').
    then(function() {
      console.log('Elapsed time: ' + (new Date().getTime() - start) + ' ms');
    });

Example #2: Synchronizing a test with an AJAX application:

var button = driver.findElement(By.id('compose-button'));
button.click();
driver.executeAsyncScript(
    'var callback = arguments[arguments.length - 1];' +
    'mailClient.getComposeWindowWidget().onload(callback);');
driver.switchTo().frame('composeWidget');
driver.findElement(By.id('to')).sendKEys('dog@example.com');

Example #3: Injecting a XMLHttpRequest and waiting for the result. In this example, the inject script is specified with a function literal. When using this format, the function is converted to a string for injection, so it should not reference any symbols not defined in the scope of the page under test.

driver.executeAsyncScript(function() {
  var callback = arguments[arguments.length - 1];
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "/resource/data.json", true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      callback(xhr.resposneText);
    }
  }
  xhr.send('');
}).then(function(str) {
  console.log(JSON.parse(str)['food']);
});

Parameters

  • script: string

    The script to execute.

  • var_args?: Array<any> optional

    The arguments to pass to the script.

Returns

Promise

A promise that will resolve to the scripts return value.

public executeAsyncScript(script: any, var_args?: Array<any>): Promise

Parameters

  • script: any
  • var_args?: Array<any> optional

Returns

Promise

public executeScript(script: string, var_args?: Array<any>): Promise

Schedules a command to execute JavaScript in the context of the currently selected frame or window. The script fragment will be executed as the body of an anonymous function. If the script is provided as a function object, that function will be converted to a string for injection into the target window.

Any arguments provided in addition to the script will be included as script arguments and may be referenced using the {@code arguments} object. Arguments may be a boolean, number, string, or {@code webdriver.WebElement}. Arrays and objects may also be used as script arguments as long as each item adheres to the types previously mentioned.

The script may refer to any variables accessible from the current window. Furthermore, the script will execute in the window's context, thus {@code document} may be used to refer to the current document. Any local variables will not be available once the script has finished executing, though global variables will persist.

If the script has a return value (i.e. if the script contains a return statement), then the following steps will be taken for resolving this functions return value:

  • For a HTML element, the value will resolve to a {@code webdriver.WebElement}
  • Null and undefined return values will resolve to null
  • Booleans, numbers, and strings will resolve as is
  • Functions will resolve to their string representation
  • For arrays and objects, each member item will be converted according to the rules above

Parameters

  • script: string

    The script to execute.

  • var_args?: Array<any> optional

    The arguments to pass to the script.

Returns

Promise

A promise that will resolve to the scripts return value.

public executeScript(script: any, var_args?: Array<any>): Promise

Parameters

  • script: any
  • var_args?: Array<any> optional

Returns

Promise

public findElement(locatorOrElement: Locator, var_args?: Array<any>): WebElement

Schedule a command to find an element on the page. If the element cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned by the driver. Unlike other commands, this error cannot be suppressed. In other words, scheduling a command to find an element doubles as an assert that the element is present on the page. To test whether an element is present on the page, use {@code #isElementPresent} instead.

The search criteria for find an element may either be a {@code webdriver.Locator} object, or a simple JSON object whose sole key is one of the accepted locator strategies, as defined by {@code webdriver.Locator.Strategy}. For example, the following two statements are equivalent:

var e1 = driver.findElement(By.id('foo'));
var e2 = driver.findElement({id:'foo'});

When running in the browser, a WebDriver cannot manipulate DOM elements directly; it may do so only through a {@link webdriver.WebElement} reference. This function may be used to generate a WebElement from a DOM element. A reference to the DOM element will be stored in a known location and this driver will attempt to retrieve it through {@link #executeScript}. If the element cannot be found (eg, it belongs to a different document than the one this instance is currently focused on), a {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned.

Parameters

  • locatorOrElement: Locator

    The locator strategy to use when searching for the element, or the actual DOM element to be located by the server.

  • var_args?: Array<any> optional

    Arguments to pass to {@code #executeScript} if using a JavaScript locator. Otherwise ignored.

Returns

WebElement

A WebElement that can be used to issue commands against the located element. If the element is not found, the element will be invalidated and all scheduled commands aborted.

public findElement(locatorOrElement: any, var_args?: Array<any>): WebElement

Parameters

  • locatorOrElement: any
  • var_args?: Array<any> optional

Returns

WebElement

public findElements(locator: Locator, var_args?: Array<any>): Promise

Schedule a command to search for multiple elements on the page.

Parameters

  • locator: Locator

    The locator strategy to use when searching for the element.

  • var_args?: Array<any> optional

    Arguments to pass to {@code #executeScript} if using a JavaScript locator. Otherwise ignored.

Returns

Promise

A promise that will be resolved to an array of the located {@link webdriver.WebElement}s.

public findElements(locator: any, var_args?: Array<any>): Promise

Parameters

  • locator: any
  • var_args?: Array<any> optional

Returns

Promise

public get(url: string): Promise

Schedules a command to navigate to the given URL.

Parameters

  • url: string

    The fully qualified URL to open.

Returns

Promise

A promise that will be resolved when the document has finished loading.

public getAllWindowHandles(): Promise

Schedules a command to retrieve the current list of available window handles.

Returns

Promise

A promise that will be resolved with an array of window handles.

public getCapabilities(): Promise

Returns

Promise

A promise that will resolve with the this instance's capabilities.

public getCurrentUrl(): Promise

Schedules a command to retrieve the URL of the current page.

Returns

Promise

A promise that will be resolved with the current URL.

public getLocationAbsUrl(): Promise

Returns the current absolute url from AngularJS.

Returns

Promise

public getPageSource(): Promise

Schedules a command to retrieve the current page's source. The page source returned is a representation of the underlying DOM: do not expect it to be formatted or escaped in the same way as the response sent from the web server.

Returns

Promise

A promise that will be resolved with the current page source.

public getSession(): Promise

Returns

Promise

A promise for this client's session.

public getTitle(): Promise

Schedules a command to retrieve the current page's title.

Returns

Promise

A promise that will be resolved with the current page's title.

public getWindowHandle(): Promise

Schedules a command to retrieve they current window handle.

Returns

Promise

A promise that will be resolved with the current window handle.

public isElementPresent(locatorOrElement: Locator, var_args?: Array<any>): Promise

Schedules a command to test if an element is present on the page.

If given a DOM element, this function will check if it belongs to the document the driver is currently focused on. Otherwise, the function will test if at least one element can be found with the given search criteria.

Parameters

  • locatorOrElement: Locator

    The locator strategy to use when searching for the element, or the actual DOM element to be located by the server.

  • var_args?: Array<any> optional

    Arguments to pass to {@code #executeScript} if using a JavaScript locator. Otherwise ignored.

Returns

Promise

A promise that will resolve to whether the element is present on the page.

public isElementPresent(locatorOrElement: any, var_args?: Array<any>): Promise

Parameters

  • locatorOrElement: any
  • var_args?: Array<any> optional

Returns

Promise

public manage(): WebDriverOptions

Returns

WebDriverOptions

The options interface for this instance.

public navigate(): WebDriverNavigation

Returns

WebDriverNavigation

The navigation interface for this instance.

public quit(): Promise

Schedules a command to quit the current session. After calling quit, this instance will be invalidated and may no longer be used to issue commands against the browser.

Returns

Promise

A promise that will be resolved when the command has completed.

public schedule(command: Command, description: string): Promise

Schedules a {@code webdriver.Command} to be executed by this driver's {@code webdriver.CommandExecutor}.

Parameters

  • command: Command

    The command to schedule.

  • description: string

    A description of the command for debugging.

Returns

Promise

A promise that will be resolved with the command result.

public sleep(ms: number): Promise

Schedules a command to make the driver sleep for the given amount of time.

Parameters

  • ms: number

    The amount of time, in milliseconds, to sleep.

Returns

Promise

A promise that will be resolved when the sleep has finished.

public switchTo(): WebDriverTargetLocator

Returns

WebDriverTargetLocator

The target locator interface for this instance.

public takeScreenshot(): Promise

Schedule a command to take a screenshot. The driver makes a best effort to return a screenshot of the following, in order of preference:

  1. Entire page
  2. Current window
  3. Visible portion of the current frame
  4. The screenshot of the entire display containing the browser

Returns

Promise

A promise that will be resolved to the screenshot as a base-64 encoded PNG.

public wait(fn: () => any, timeout: number, opt_message?: string): Promise

Schedules a command to wait for a condition to hold, as defined by some user supplied function. If any errors occur while evaluating the wait, they will be allowed to propagate.

Parameters

  • fn: () => any

    The function to evaluate as a wait condition.

  • timeout: number

    How long to wait for the condition to be true.

  • opt_message?: string optional

    An optional message to use if the wait times out.

Returns

Promise

A promise that will be resolved when the wait condition has been satisfied.

public waitForAngular(): Promise

Instruct webdriver to wait until Angular has finished rendering and has no outstanding $http calls before continuing.

Returns

Promise

A promise that will resolve to the scripts return value.

public wrapWebElement(element: WebElement): WebElement

Wrap a webdriver.WebElement with protractor specific functionality.

Parameters

Returns

WebElement

the wrapped web element.