From 4cf3256fe813b0121cc69f8b794ee6bb68905971 Mon Sep 17 00:00:00 2001 From: Craig Nishina Date: Wed, 14 Sep 2016 16:12:30 -0700 Subject: [PATCH] types(selenium): update selenium-webdriver to 2.53.1 - update from selenium-webdriver 2.44 to 2.53.1 - remove dependencies for selenium-webdriver 2.44: - protractor - protractor-helpers - protractor-http-mock --- protractor-helpers/index.d.ts | 111 - .../protractor-helpers-tests.ts | 116 - protractor-helpers/tsconfig.json | 19 - protractor-http-mock/index.d.ts | 284 -- .../protractor-http-mock-tests.ts | 302 -- protractor-http-mock/tsconfig.json | 19 - protractor/angular-protractor-tests.ts | 483 -- protractor/index.d.ts | 1849 -------- protractor/tsconfig.json | 19 - selenium-webdriver/index.d.ts | 4116 +++++++++++------ .../selenium-webdriver-tests.ts | 249 +- 11 files changed, 2726 insertions(+), 4841 deletions(-) delete mode 100644 protractor-helpers/index.d.ts delete mode 100644 protractor-helpers/protractor-helpers-tests.ts delete mode 100644 protractor-helpers/tsconfig.json delete mode 100644 protractor-http-mock/index.d.ts delete mode 100644 protractor-http-mock/protractor-http-mock-tests.ts delete mode 100644 protractor-http-mock/tsconfig.json delete mode 100644 protractor/angular-protractor-tests.ts delete mode 100644 protractor/index.d.ts delete mode 100644 protractor/tsconfig.json diff --git a/protractor-helpers/index.d.ts b/protractor-helpers/index.d.ts deleted file mode 100644 index 00df7cff98..0000000000 --- a/protractor-helpers/index.d.ts +++ /dev/null @@ -1,111 +0,0 @@ -// Type definitions for protractor-helpers v1.0.0 -// Project: https://github.com/wix/protractor-helpers -// Definitions by: John Cant -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -/// -/// - -// ElementArrayFinder - -declare namespace protractor { - interface ElementArrayFinder { - getByText(text: string) : protractor.ElementFinder; - $$data(hook: string) : protractor.ElementArrayFinder; - } - - interface ElementFinder { - $data(hook: string) : protractor.ElementFinder; - } -} - -// Globals - -declare function $data(hook: string) : protractor.ElementFinder; -declare function $$data(hook: string) : protractor.ElementArrayFinder; - - -// Locators - -// TODO - find out about result of querySelector and querySelector all. -// Are they Locator s? -declare namespace protractor { - interface IProtractorLocatorStrategy { - dataHook(hook: string, optParentElement?: protractor.ElementFinder, optRootSelector?: string) : webdriver.Locator; - dataHookAll(hook: string, optParentElement?: protractor.ElementFinder, optRootSelector?: string) : webdriver.Locator; - } -} - -// Matchers -// TODO - Typescript doesn't really help much here -// we don't know what type is being tested. -// Fixing this would require modifying the -// jasmine d.ts. - -declare namespace jasmine { - interface Matchers { - toBePresent() : boolean; - toBeDisplayed() : boolean; - toHaveCountOf(expectedCount : number) : boolean; - toHaveText(expectedText : string) : boolean; - toMatchRegex(regex : RegExp) : boolean; - toMatchMoney(expectedValue : number, currencySymbol? : string) : boolean; - toMatchMoneyWithFraction(expectedValue : number, currencySymbol?: string) : boolean; - toHaveValue(actual: string | number) : boolean; - toHaveClass(className : string) : boolean; - toHaveUrl(url : string) : boolean; - toBeDisabled() : boolean; - toBeChecked() : boolean; - toBeValid() : boolean; - toBeInvalid() : boolean; - toBeInvalidRequired() : boolean; - // Copied definitions from angular-translate. - toMatchTranslated(translationId : string, interpolateParams? : any) : boolean; - toMatchTranslated(translationId : string[], interpolateParams? : any) : boolean; - } -} - - -declare module "protractor-helpers" { - - function not(arg: webdriver.promise.IThenable) : webdriver.promise.IThenable; - - // Copied definitions from angular-translate. - function translate(translationId: string, interpolateParams?: any): webdriver.promise.IThenable; - function translate(translationId: string[], interpolateParams?: any): webdriver.promise.IThenable<{ [key: string]: string }>; - - function safeGet(url: string) : void; - - function maximizeWindow(width?: number, height?: number) : void; // TODO - function resetPosition() : void; - function moveToElement(hook: string) : void; - function displayHover(element: protractor.ElementFinder) : void; - - function waitForElement(element: protractor.ElementFinder, timeout?: number) : void; - function waitForElementToDisappear(element: protractor.ElementFinder, timeout?: number) : void; - - function selectOptionByText(select: protractor.ElementFinder, text: string) : void; - function selectOptionByIndex(select: protractor.ElementFinder, index: number) : void; - - function selectOption(option: protractor.ElementFinder) : void - - function isFirefox() : boolean; - function isIE() : boolean; - - function createMessage(actual : string, message : string, isNot : any) : string; // isNot : boolean too inflexible - function createMessage(actual : protractor.ElementFinder, message : string, isNot : any) : string; // isNot : boolean too inflexible - function createMessage(actual : protractor.ElementArrayFinder, message : string, isNot : any) : string; // isNot : boolean too inflexible - - function clearAndSetValue(input : protractor.ElementFinder, value : string) : void; // TODO - sendKeys(value) - - function hasClass(element: protractor.ElementFinder, className: string) : webdriver.promise.IThenable; - function hasValue(element: protractor.ElementFinder, expectedValue: string) : webdriver.promise.IThenable; - function hasValue(element: protractor.ElementFinder, expectedValue: number) : webdriver.promise.IThenable; - function hasLink(element: protractor.ElementFinder, url: string) : webdriver.promise.IThenable; - function isDisabled(element: protractor.ElementFinder) : webdriver.promise.IThenable; - function isChecked(element: protractor.ElementFinder) : webdriver.promise.IThenable; - function getFilteredConsoleErrors() : webdriver.promise.IThenable; // TODO - discuss handling in IE - -} - diff --git a/protractor-helpers/protractor-helpers-tests.ts b/protractor-helpers/protractor-helpers-tests.ts deleted file mode 100644 index 269390080e..0000000000 --- a/protractor-helpers/protractor-helpers-tests.ts +++ /dev/null @@ -1,116 +0,0 @@ - - -import helpers = require('protractor-helpers'); - -declare var $$: any, $: any, by: any, element: any; // ?? - -function testElementArrayFinder() { - - var single1 : protractor.ElementFinder = $$('.foo').getByText('Hello'); - var multiple : protractor.ElementArrayFinder = $$('.foo').$$data('Hello'); - -} - -function testElementFinder () { - var single2 : protractor.ElementFinder = $('.foo').$data('Hello'); -} - -function testGlobals() { - - var single : protractor.ElementFinder = $data('Hello'); - var multiple : protractor.ElementArrayFinder = $$data('Hello'); - -} - -function testHelpers() { - - var q0 : webdriver.promise.IThenable = helpers.not($('.foo').isDisplayed()); - // TODO - Check impl - var q1 : webdriver.promise.IThenable<{[key: string]:string}> = helpers.translate(["foo", "bar"]); - var q2 : webdriver.promise.IThenable<{[key: string]:string}> = helpers.translate(["foo", "bar"], {name: 'foo'}); - var q3 : webdriver.promise.IThenable = helpers.translate("foo"); - var q4 : webdriver.promise.IThenable = helpers.translate("foo", {name: 'foo'}); - - helpers.safeGet('https://foo/'); - - helpers.maximizeWindow(500, 500); - helpers.maximizeWindow(500); - helpers.maximizeWindow(undefined, 500); - helpers.maximizeWindow(); - - helpers.resetPosition(); - helpers.moveToElement(".foo"); // TODO - ? - - helpers.displayHover($('.foo')); - - helpers.waitForElement($('.foo')); - helpers.waitForElement($('.foo'), 1000); - helpers.waitForElementToDisappear($('.foo'));; - helpers.waitForElementToDisappear($('.foo'), 1000); - - helpers.selectOptionByText($('select'), "GB"); - helpers.selectOptionByIndex($('select'), 1); - - helpers.selectOption($$('select option').first()); - - var ff : boolean = helpers.isFirefox(); - var ie : boolean = helpers.isIE(); - - var msg : string = helpers.createMessage("actual", "message", true); - var msg : string = helpers.createMessage($('.foo'), "message", true); - var msg : string = helpers.createMessage($$('.foo'), "message", true); - - helpers.clearAndSetValue($('input'), 'Foo'); - - var hc : webdriver.promise.IThenable = helpers.hasClass($('.foo'), 'foo'); - - var hv : webdriver.promise.IThenable = helpers.hasValue($('input[type=text]'), 'foo'); - var hv1 : webdriver.promise.IThenable = helpers.hasValue($('input[type=numeric]'), 12); - var hl : webdriver.promise.IThenable = helpers.hasLink($('div'), 'http://foo.com'); - var disabled : webdriver.promise.IThenable = helpers.isDisabled($('foo')); - var checked : webdriver.promise.IThenable = helpers.isChecked($('foo')); - - var q5 : webdriver.promise.IThenable = helpers.getFilteredConsoleErrors(); - -} - -function testLocators() { - - element(by.dataHook("foo")); - element(by.dataHook("foo", $('.parentfoo'))); - element(by.dataHook("foo", undefined , ".foo")); - element(by.dataHook("foo", $('.parentfoo'), ".foo")); // TODO - This might not make much sense, but can technically be used in working code. Opinions welcome - - element.all(by.dataHook("foo")); - element.all(by.dataHook("foo", $('parentfoo'))); - element.all(by.dataHook("foo", undefined , ".foo")); - element.all(by.dataHook("foo", $('parentfoo'), ".foo")); // TODO - This might not make much sense, but can technically be used in working code. Opinions welcome - -} - -function testMatchers() { - - var expectResult : boolean; - expectResult = expect($('.foo')).toBePresent(); - expectResult = expect($('.foo')).toBeDisplayed(); - expectResult = expect($$('.foo').count()).toHaveCountOf(1); - expectResult = expect($('.foo')).toHaveText("bla"); - expectResult = expect($('.foo')).toMatchRegex(/bla/); - expectResult = expect($('.foo').getText()).toMatchMoney(123, "£"); - expectResult = expect($('.foo').getText()).toMatchMoneyWithFraction(123.45, "£"); - expectResult = expect($('input')).toHaveValue(12); - expectResult = expect($('input')).toHaveValue("bla"); - expectResult = expect($('.foo')).toHaveClass("foo"); - expectResult = expect($('.foo')).toHaveUrl('https://foo.com'); - expectResult = expect($('.foo')).toBeDisabled(); - expectResult = expect($('.foo')).toBeChecked(); - expectResult = expect($('.foo')).toBeValid(); - expectResult = expect($('.foo')).toBeInvalid(); - expectResult = expect($('.foo')).toBeInvalidRequired(); - expectResult = expect($('.foo')).toMatchTranslated("foo"); - expectResult = expect($('.foo')).toMatchTranslated("foo", {foo: "bar"}); - expectResult = expect($('.foo')).toMatchTranslated(["foo"]); - expectResult = expect($('.foo')).toMatchTranslated(["foo", "bla"], {foo: "bar"}); - -} - diff --git a/protractor-helpers/tsconfig.json b/protractor-helpers/tsconfig.json deleted file mode 100644 index e180a4d570..0000000000 --- a/protractor-helpers/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "protractor-helpers-tests.ts" - ] -} \ No newline at end of file diff --git a/protractor-http-mock/index.d.ts b/protractor-http-mock/index.d.ts deleted file mode 100644 index 5f9dbcd79a..0000000000 --- a/protractor-http-mock/index.d.ts +++ /dev/null @@ -1,284 +0,0 @@ -// Type definitions for protractor-http-mock -// Project: https://github.com/atecarlos/protractor-http-mock -// Definitions by: Crevil -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace mock { - interface ProtractorHttpMock { - /** - * Instantiate mock module. This must be done before the browser connects. - * - * @param mocks An array of mock modules to load into the application. - * @param plugins An array of Plugin objects. - * @param skipDefaults Set true to skip loading of default mocks. - */ - (mocks?: Array>, plugins?: Array, skipDefaults?: boolean): ProtractorHttpMock; - - /** - * Instantiate mock module. This must be done before the browser connects. - * - * @param mocks An array of mock modules to load into the application. - * @param plugins An array of NPM modules as strings. - * @param skipDefaults Set true to skip loading of default mocks. - */ - (mocks?: Array>, plugins?: Array, skipDefaults?: boolean): ProtractorHttpMock; - - /** - * Instantiate mock modules from files. This must be done before the browser connects. - * - * @param mocks An array of mock module names relative to the rootDirectory configuration. - * @param plugins An array of Plugin objects. - * @param skipDefaults Set true to skip loading of default mocks. - */ - (mocks: Array, plugins?: Array, skipDefaults?: boolean): ProtractorHttpMock; - - /** - * Instantiate mock modules from files. This must be done before the browser connects. - * - * @param mocks An array of mock module names relative to the rootDirectory configuration. - * @param plugins An array of NPM modules as strings. - * @param skipDefaults Set true to skip loading of default mocks. - */ - (mocks: Array, plugins?: Array, skipDefaults?: boolean): ProtractorHttpMock; - - /** - * Clean up. - * Typically done in the afterEach call to ensure the teardown - * is executed regardless of what happens in the test execution. - */ - teardown(): void; - - /** - * Returns a promise that will be resolved with an array of - * all matched HTTP requests. - */ - requestsMade(): webdriver.promise.Promise>; - - /** - * Returns a promise that will be resolved with a true boolean - * when all matched HTTP requests are cleared. - */ - clearRequests(): webdriver.promise.Promise; - - /** - * Module configuration to setup - */ - config: { - /** - * Mocks directory where mock files are located. - * Default: process.cwd() - */ - rootDirectory?: string; - - /** - * Path to protractor configuration file. - * Default: protractor.conf - */ - protractorConfig?: string; - }; - - /** - * Add mocks during test execution. - * Returns a promise that will be resolved with a true boolean - * when mocks are added. - * - * @param mocks An array of mock modules to load into the application. - */ - add(mocks: Array>): webdriver.promise.Promise; - - /** - * Remove mocks during test execution. - * Returns a promise that will be resolved with a true boolean - * when the supplied mocks are removed. - * - * @param mocks An array of mock modules to remove from the application. - */ - remove(mocks: Array>): webdriver.promise.Promise; - } - - /** - * Matched request. - */ - interface ReceivedRequest { - url: string; - method: requests.Method; - } - - /** - * Plugin for custom matching logic. - */ - interface Plugin { - /** - * Match function. - * Return a truthy value to indicate successfull match. - * - * @param mockRequest The mock to compare request with. - * @param requestConfig The request object to compare mock with. - */ - match(mockRequest: requests.AllRequests, requestConfig: requests.AllRequests): boolean; - } - - /** - * Plugin for custom matching logic. - */ - interface Plugin { - /** - * Match function. - * Return a truthy value to indicate successfull match. - * - * @param mockRequest The mock to compare request with. - * @param requestConfig The request object to compare mock with. - */ - match(mockRequest: requests.AllRequests, requestConfig: requests.AllRequests): boolean; - } - - namespace requests { - /** - * Request methods type - */ - type Method = "GET" | "POST" | "DELETE" | "PUT" | "HEAD" | "PATCH" | "JSONP"; - - /** - * All available request types. - */ - type AllRequests = Get | - PostData | - Post | - Head | - Delete | - Put | - Patch | - Jsonp; - - /** - * GET request mock. - */ - interface Get { - request: { - method: Method; - path: string; - regex?: boolean; - params?: Object; - queryString?: Object; - headers?: Object; - interceptedRequest?: boolean; - interceptedAnonymousRequest?: boolean; - }; - response: { - status?: number; - data: TResponse; - }; - } - - /** - * POST request mock with payload. - */ - interface PostData { - request: { - method: Method; - path: string; - regex?: boolean; - data: TPayload; - }; - response: { - status?: number; - data: TResponse; - }; - } - - /** - * POST request mock. - */ - interface Post { - request: { - method: Method; - path: string; - regex?: boolean; - }; - response: { - status?: number; - data: TResponse; - }; - } - - /** - * HEAD request mock. - */ - interface Head { - request: { - method: Method; - path: string; - regex?: boolean; - }; - response: { - status?: number; - data: TResponse; - }; - } - - /** - * HTTP Delete request mock. - */ - interface Delete { - request: { - method: Method; - path: string; - regex?: boolean; - }; - response: { - status?: number; - data: TResponse; - }; - } - - /** - * PUT request mock. - */ - interface Put { - request: { - method: Method; - path: string; - regex?: boolean; - }; - response: { - status?: number; - data: TResponse; - }; - } - - /** - * PATCH request mock. - */ - interface Patch { - request: { - method: Method; - path: string; - regex?: boolean; - }; - response: { - status?: number; - data: TResponse; - }; - } - - /** - * JSONP request mock. - */ - interface Jsonp { - request: { - method: Method; - path: string; - regex?: boolean; - }; - response: { - status?: number; - data: TResponse; - }; - } - } -} - -declare var mock: mock.ProtractorHttpMock; -export = mock; diff --git a/protractor-http-mock/protractor-http-mock-tests.ts b/protractor-http-mock/protractor-http-mock-tests.ts deleted file mode 100644 index 08b97fd09f..0000000000 --- a/protractor-http-mock/protractor-http-mock-tests.ts +++ /dev/null @@ -1,302 +0,0 @@ -import mock = require("protractor-http-mock"); - -function TestConfig() { - mock.config = { - rootDirectory: "root", - protractorConfig: "protractor.conf.js" - }; -} - -function TestCtorOverloads() { - let del: mock.requests.Delete = { - request: { - path: 'path', - method: 'DELETE' - }, - response: { - status: 400, - data: 1 - } - }; - let put: mock.requests.Put = { - request: { - path: 'path', - method: 'PUT' - }, - response: { - status: 400, - data: 1 - } - }; - let plugin: mock.Plugin = { - match: (mockRequest: mock.requests.Delete, requestConfig: mock.requests.AllRequests) => { - if (requestConfig.request.method && mockRequest.request.method) { - return true; - } - - return false; - } - }; - - let noParam: mock.ProtractorHttpMock = mock(); - let emptyArray: mock.ProtractorHttpMock = mock([]); - let mockFiles: mock.ProtractorHttpMock = mock(['mock1', 'mock2']); - let mocks: mock.ProtractorHttpMock = mock([del, put]); - - let mockFilesNpmPlugins: mock.ProtractorHttpMock = mock(['mock1'], ['plugin']); - let mocksWithNpmPlugins: mock.ProtractorHttpMock = mock([del, put], ['plugin']); - - let pluginMocks: mock.ProtractorHttpMock = mock([del, put], [plugin]); - - let mockFilesNpmPluginsSkipDefaults: mock.ProtractorHttpMock = mock(['mock1'], ['plugin'], true); - let skipDefaults: mock.ProtractorHttpMock = mock([del, put], [plugin], true); -} - -function TestTeardown() { - mock.teardown(); -} - -function TestRequestsMade() { - let values: Array; - mock.requestsMade().then(v => values = v); -} - -function TestClearRequests() { - let promiseValue: boolean; - mock.clearRequests().then(value => { - promiseValue = value; - }); -} - -function TestDynamicAdd() { - let put: mock.requests.Put = { - request: { - path: "path", - method: "PUT" - }, - response: { - status: 400, - data: 1 - } - }; - let resolved: boolean; - mock.add([put]).then(r => resolved = r); -} - -function TestDyanmicRemove() { - let put: mock.requests.Put = { - request: { - path: "path", - method: "PUT" - }, - response: { - status: 400, - data: 1 - } - }; - let resolved: boolean; - mock.remove([put]).then(r => resolved = r); -} - -function TestGetRequestDefinitions() { - let getMinium: mock.requests.Get = { - request: { - path: 'path', - method: 'GET', - regex: true - }, - response: { - data: 1, - status: 500 - } - }; - - let getParams: mock.requests.Get = { - request: { - path: 'path', - method: 'GET', - regex: true, - params: { - param1: 'param1', - param2: 2 - } - }, - response: { - data: 1, - status: 500 - } - }; - - let post: mock.requests.Post = { - request: { - path: 'path', - method: 'POST', - regex: true - }, - response: { - data: 1, - status: 500 - } - }; - - let getQueryString: mock.requests.Get = { - request: { - path: 'path', - method: 'GET', - regex: true, - queryString: { - query1: 'query1', - query2: 2 - } - }, - response: { - data: 1, - status: 500 - } - }; - - let getHeaders: mock.requests.Get = { - request: { - path: 'path', - method: 'GET', - regex: true, - headers: { - head1: 'head1', - head2: 'head2' - } - }, - response: { - data: 1, - status: 500 - } - }; -} - -function TestPostRequestDefinitions() { - let post: mock.requests.Post = { - request: { - path: 'path', - method: 'POST', - regex: true - }, - response: { - data: 1, - status: 500 - } - }; - - let postData: mock.requests.PostData = { - request: { - path: 'path', - method: 'POST', - data: 'data', - regex: true - }, - response: { - data: 1, - status: 500 - } - }; -} - -function TestHeadRequestDefinitions() { - let head: mock.requests.Head = { - request: { - path: 'path', - method: 'HEAD', - regex: true - }, - response: { - status: 500, - data: 1 - } - }; -} - -function TestDeleteRequestDefinitions() { - let del: mock.requests.Delete = { - request: { - path: 'path', - method: 'DELETE', - regex: true - }, - response: { - status: 500, - data: 1 - } - }; -} - -function TestPutRequestDefinitions() { - let put: mock.requests.Put = { - request: { - path: 'path', - method: 'PUT', - regex: true - }, - response: { - status: 500, - data: 1 - } - }; -} - -function TestPatchRequestDefinitions() { - let patch: mock.requests.Patch = { - request: { - path: 'path', - method: 'PATCH', - regex: true - }, - response: { - status: 500, - data: 1 - } - }; -} - -function TestJsonpRequestDefinitions() { - let jsonp: mock.requests.Jsonp = { - request: { - path: 'path', - method: 'JSONP', - regex: true - }, - response: { - status: 500, - data: 1 - } - }; -} - -function TestRuntimeMocks() { - mock.add([{ - request: { - path: '/users', - method: 'GET', - params: { - name: 'Charlie' - } - }, - response: { - data: { - name: 'Override' - } - } - }]); - - mock.remove([{ - request: { - path: '/users', - method: 'GET', - params: { - name: 'Charlie' - } - }, - response: { - data: { - name: 'Override' - } - } - }]); -} diff --git a/protractor-http-mock/tsconfig.json b/protractor-http-mock/tsconfig.json deleted file mode 100644 index 8d6b5822e4..0000000000 --- a/protractor-http-mock/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "protractor-http-mock-tests.ts" - ] -} \ No newline at end of file diff --git a/protractor/angular-protractor-tests.ts b/protractor/angular-protractor-tests.ts deleted file mode 100644 index 0a7ae85357..0000000000 --- a/protractor/angular-protractor-tests.ts +++ /dev/null @@ -1,483 +0,0 @@ - - -function TestWebDriverExports() { - var button: number = protractor.Button.LEFT; - - var key: string = protractor.Key.ADD; - var chord: string = protractor.Key.chord(protractor.Key.NUMPAD0, protractor.Key.NUMPAD1); - - var driver: protractor.WebDriver = new protractor.Builder(). - withCapabilities(protractor.Capabilities.chrome()). - build(); - var baseDriver: webdriver.WebDriver = driver; - - var action: protractor.ActionSequence = new protractor.ActionSequence(driver); - var baseAction: webdriver.ActionSequence = action; - - var browser: string = protractor.Browser.ANDROID; - - var builder: protractor.Builder = new protractor.Builder(); - var baseBuilder: webdriver.Builder = builder; - - var capability: string = protractor.Capability.BROWSER_NAME; - - var capabilities: protractor.Capabilities = protractor.Capabilities.chrome(); - var baseCapabilities: webdriver.Capabilities = capabilities; - - var commandName: string = protractor.CommandName.CLICK_ELEMENT; - - var command: protractor.Command = new protractor.Command(protractor.CommandName.CLICK); - var baseCommand: webdriver.Command = command; - - var eventEmitter: protractor.EventEmitter = new protractor.EventEmitter(); - var baseEventEmitter: webdriver.EventEmitter = eventEmitter; - - var webElement: protractor.WebElement = new protractor.WebElement(driver, new protractor.promise.Promise()); - var baseWebElement: webdriver.WebElement = webElement; - - var locator: webdriver.Locator = by.id('abc'); - - var session: protractor.Session = new protractor.Session('ABC', webdriver.Capabilities.android()); - var baseSession: webdriver.Session = session; - - locator = protractor.By.name('name'); - - var driver: protractor.WebDriver = new protractor.WebDriver(session, {}); - driver = new protractor.WebDriver(session, {}, new webdriver.promise.ControlFlow()); - var baseDriver: webdriver.WebDriver = driver; - - var webElement: protractor.WebElement = new protractor.WebElement(driver, { ELEMENT: 'abc' }); - var baseWebElement: webdriver.WebElement = webElement; - - var webElementPromise: protractor.WebElementPromise = new protractor.WebElementPromise(driver, { ELEMENT: 'abc' }); - var baseWebElementPromise: webdriver.WebElementPromise = webElementPromise; -} - -function TestWebDriverErrorModule() { - var errorCode: number = protractor.error.ErrorCode.ELEMENT_NOT_VISIBLE; - var error: protractor.error.Error = new protractor.error.Error(protractor.error.ErrorCode.ELEMENT_NOT_VISIBLE); - var baseError: webdriver.error.Error = error; -} - -function TestWebDriverLoggingModule() { - var levelName: string = protractor.logging.Level.ALL.name; - var loggingType: string = protractor.logging.Type.CLIENT; - - var level: webdriver.logging.ILevel = protractor.logging.Level.ALL; - - var entry: protractor.logging.Entry = new protractor.logging.Entry(protractor.logging.Level.ALL, 'Message'); - var baseEntry: webdriver.logging.Entry = entry; - - level = protractor.logging.getLevel('DEBUG'); - - var prefs: protractor.logging.Preferences = new protractor.logging.Preferences(); -} - -function TestWebDriverPromiseModule() { - var cancelError: protractor.promise.CancellationError = new protractor.promise.CancellationError(); - cancelError = new protractor.promise.CancellationError('message'); - var baseCancelError: webdriver.promise.CancellationError = cancelError; - - var thenable: protractor.promise.Thenable = new protractor.promise.Thenable(); - var baseThenable: webdriver.promise.Thenable = thenable; - - var promise: protractor.promise.Promise = new protractor.promise.Promise(); - var basePromise: webdriver.promise.Promise = promise; - - var deferred: protractor.promise.Deferred = new protractor.promise.Deferred(); - var baseDeferred: webdriver.promise.Deferred = deferred; - - var flow: protractor.promise.ControlFlow = new protractor.promise.ControlFlow(); - var baseFlow: webdriver.promise.ControlFlow = flow; - - var arrayPromise: protractor.promise.Promise = protractor.promise.all([new protractor.promise.Promise(), new protractor.promise.Promise()]); - - protractor.promise.asap(promise, function (value: any) { return true; }); - protractor.promise.asap(promise, function (value: any) { }, function (err: any) { return 'ABC'; }); - - promise = protractor.promise.checkedNodeCall(function (err: any, value: any) { return 123; }); - - promise = protractor.promise.consume(function () { - return 5; - }); - promise = protractor.promise.consume(function () { - return 5; - }, this); - promise = protractor.promise.consume(function () { - return 5; - }, this, 1, 2, 3); - - flow = protractor.promise.controlFlow(); - - promise = protractor.promise.createFlow(function (newFlow: webdriver.promise.ControlFlow) { }); - - deferred = protractor.promise.defer(); - - promise = protractor.promise.delayed(123); - - var numbersPromise: protractor.promise.Promise = protractor.promise.filter([1, 2, 3], function (el: number, index: number, arr: number[]) { - return true; - }); - numbersPromise = protractor.promise.filter([1, 2, 3], function (el: number, index: number, arr: number[]) { - return true; - }, this); - numbersPromise = protractor.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { - return true; - }); - numbersPromise = protractor.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { - return true; - }, this); - - numbersPromise = protractor.promise.map([1, 2, 3], function (el: number, index: number, arr: number[]) { - return true; - }); - numbersPromise = protractor.promise.map([1, 2, 3], function (el: number, index: number, arr: number[]) { - return true; - }, this); - numbersPromise = protractor.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { - return true; - }); - numbersPromise = protractor.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { - return true; - }, this); - - promise = protractor.promise.fulfilled(); - promise = protractor.promise.fulfilled({ a: 123 }); - - promise = protractor.promise.fullyResolved({ a: 123 }); - - var bool: boolean = protractor.promise.isGenerator(function () { }); - var bool: boolean = protractor.promise.isPromise('ABC'); - - promise = protractor.promise.rejected({ a: 123 }); - - protractor.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); - - promise = protractor.promise.when(promise, function (value: any) { return 123; }, function (err: Error) { return 123; }); -} - -function TestWebDriverStacktraceModule() { - var bool: boolean = protractor.stacktrace.BROWSER_SUPPORTED; - - var frame: protractor.stacktrace.Frame = new protractor.stacktrace.Frame(); - var baseFrame: webdriver.stacktrace.Frame = frame; - - var snapshot: protractor.stacktrace.Snapshot = new protractor.stacktrace.Snapshot(); - var baseSnapshot: webdriver.stacktrace.Snapshot = snapshot; - - var err: Error = protractor.stacktrace.format(new Error("Error")); - var frames: protractor.stacktrace.Frame[] = protractor.stacktrace.get(); -} - -function TestWebDriverUntilModule() { - var conditionB: protractor.until.Condition = new protractor.until.Condition('message', function (driver: webdriver.WebDriver) { return true; }); - var conditionBBase: webdriver.until.Condition = conditionB; - var conditionWebElement: protractor.until.Condition; - var conditionWebElements: protractor.until.Condition; - - conditionB = protractor.until.ableToSwitchToFrame(5); - var conditionAlert: protractor.until.Condition = protractor.until.alertIsPresent(); - var el: protractor.ElementFinder = element(by.id('id')); - conditionB = protractor.until.elementIsDisabled(el); - conditionB = protractor.until.elementIsEnabled(el); - conditionB = protractor.until.elementIsNotSelected(el); - conditionB = protractor.until.elementIsNotVisible(el); - conditionB = protractor.until.elementIsSelected(el); - conditionB = protractor.until.elementIsVisible(el); - conditionB = protractor.until.elementTextContains(el, 'text'); - conditionB = protractor.until.elementTextIs(el, 'text'); - conditionB = protractor.until.elementTextMatches(el, /text/); - conditionB = protractor.until.stalenessOf(el); - conditionB = protractor.until.titleContains('text'); - conditionB = protractor.until.titleIs('text'); - conditionB = protractor.until.titleMatches(/text/); - - conditionWebElement = protractor.until.elementLocated(by.id('id')); - conditionWebElements = protractor.until.elementsLocated(by.className('class')); -} - -function TestWebDriverExpectedConditionsModule() { - var conditionB: protractor.until.Condition; - var el: protractor.ElementFinder = element(by.id('id')); - - conditionB = protractor.ExpectedConditions.alertIsPresent(); - conditionB = protractor.ExpectedConditions.elementToBeClickable(el); - conditionB = protractor.ExpectedConditions.textToBePresentInElement(el, 'text'); - conditionB = protractor.ExpectedConditions.textToBePresentInElementValue(el, 'text'); - conditionB = protractor.ExpectedConditions.titleContains('text'); - conditionB = protractor.ExpectedConditions.titleIs('text'); - conditionB = protractor.ExpectedConditions.presenceOf(el); - conditionB = protractor.ExpectedConditions.stalenessOf(el); - conditionB = protractor.ExpectedConditions.visibilityOf(el); - conditionB = protractor.ExpectedConditions.invisibilityOf(el); - conditionB = protractor.ExpectedConditions.elementToBeSelected(el); - - conditionB = protractor.ExpectedConditions.not(protractor.ExpectedConditions.alertIsPresent()); - conditionB = protractor.ExpectedConditions.and(protractor.ExpectedConditions.alertIsPresent(), protractor.ExpectedConditions.elementToBeClickable(el)); - conditionB = protractor.ExpectedConditions.or(protractor.ExpectedConditions.alertIsPresent(), protractor.ExpectedConditions.elementToBeClickable(el)); -} - -function TestProtractor() { - var ptor: protractor.Protractor; - var driver: webdriver.WebDriver = new webdriver.Builder(). - withCapabilities(webdriver.Capabilities.chrome()). - build(); - - ptor = protractor.wrapDriver(driver); - ptor = protractor.wrapDriver(driver, 'baseUrl'); - ptor = protractor.wrapDriver(driver, 'baseUrl', 'rootElement'); - - ptor = browser; - - var actions: protractor.ActionSequence = ptor.actions(); - - var promise: protractor.promise.Promise = ptor.call(function () { }); - var promise: protractor.promise.Promise = ptor.call(function () { }, this); - var promise: protractor.promise.Promise = ptor.call(function (a: number, b: number, c:number) { }, this, 1, 2,3); - - promise = ptor.executeAsyncScript('SomeScript'); - promise = ptor.executeAsyncScript('SomeScript', 1, 2, 3); - promise = ptor.executeAsyncScript(function () { }); - promise = ptor.executeAsyncScript(function (a: number, b: number, c: number) { }, 1, 2, 3); - - promise = ptor.executeScript('SomeScript'); - promise = ptor.executeScript('SomeScript', 1, 2, 3); - promise = ptor.executeScript(function () { }); - promise = ptor.executeScript(function (a: number, b: number, c: number) { }, 1, 2, 3); - - ptor = browser.forkNewDriverInstance(); - ptor = browser.forkNewDriverInstance(true); - ptor = browser.forkNewDriverInstance(true, false); - - driver = ptor.driver; - var baseUrl: string = ptor.baseUrl; - var rootEl: string = ptor.rootEl; - var ignoreSynchronization: boolean = ptor.ignoreSynchronization; - var params: any = ptor.params; - ptor.resetUrl = "url"; - - ptor.debugger(); - ptor.close(); - var controlFlow: protractor.promise.ControlFlow = ptor.controlFlow(); - - var webElement: protractor.WebElement = ptor.findElement(by.css('.class')); - ptor.findElements(by.css('.class')).then(function (elements: webdriver.WebElement[]) { }); - ptor.isElementPresent(by.css('.class')).then(function (present: boolean) { }); - ptor.isElementPresent(webElement).then(function (present: boolean) { }); - - ptor.clearMockModules(); - ptor.addMockModule('name', 'script'); - ptor.addMockModule('name', function() {}); - ptor.removeMockModule('name'); - ptor.waitForAngular(); - - var elementFinder: protractor.ElementFinder; - var elementArrayFinder: protractor.ElementArrayFinder; - - elementFinder = ptor.element(by.id('ABC')); - elementFinder = ptor.$('.class'); - - elementArrayFinder = ptor.$$('.class'); - - var locationAbsUrl: webdriver.promise.Promise = ptor.getLocationAbsUrl(); - ptor.setLocation('webaddress.com'); - - var voidPromise: webdriver.promise.Promise = ptor.get('webaddress.com'); - voidPromise = ptor.get('webdaddress.com', 45); - voidPromise = ptor.quit(); - voidPromise = ptor.sleep(5000); - - ptor.refresh(); - ptor.refresh(45); - var navigation: webdriver.WebDriverNavigation = ptor.navigate(); - ptor.pause(); - ptor.pause(8080); - - ptor.getAllWindowHandles().then(function (handles: string[]) { }); - - var capabilities: protractor.promise.Promise = ptor.getCapabilities(); - - var stringPromise: webdriver.promise.Promise; - stringPromise = ptor.getCurrentUrl(); - stringPromise = ptor.getPageSource(); - stringPromise = ptor.getTitle(); - stringPromise = ptor.getWindowHandle(); - stringPromise = ptor.takeScreenshot(); - - ptor.getPageTimeout = 5000; - - var session: protractor.promise.Promise = ptor.getSession(); - - var options: webdriver.WebDriverOptions = ptor.manage(); - - promise = ptor.schedule(new protractor.Command(protractor.CommandName.ACCEPT_ALERT), 'asdf'); - - var targetLocator: webdriver.WebDriverTargetLocator = ptor.switchTo(); - - ptor.wait(protractor.until.elementLocated(by.id('id')), 5000).then(function (el: webdriver.IWebElement) { });; - ptor.wait(protractor.until.elementLocated(by.id('id')), 5000, 'message').then(function (el: webdriver.IWebElement) { });; -} - -function TestElement() { - var elementFinder: protractor.ElementFinder = element(by.id('id')); - var elementArrayFinder: protractor.ElementArrayFinder = element.all(by.className('class')); -} - -function TestElementFinder() { - var elementFinder: protractor.ElementFinder = element(by.id('id')); - var voidPromise: webdriver.promise.Promise; - var stringPromise: webdriver.promise.Promise; - var booleanPromise: webdriver.promise.Promise; - - elementFinder.getId().then(function (id: webdriver.IWebElementId) { }); - voidPromise = elementFinder.click(); - elementFinder = elementFinder.allowAnimations('string'); - voidPromise = elementFinder.sendKeys(protractor.Key.UP, protractor.Key.DOWN); - stringPromise = elementFinder.getTagName(); - stringPromise = elementFinder.getCssValue('display'); - stringPromise = elementFinder.getAttribute('atribute'); - stringPromise = elementFinder.getText(); - elementFinder.getSize().then(function (size: webdriver.ISize) { }); - elementFinder.getLocation().then(function (location: webdriver.ILocation) { }); - booleanPromise = elementFinder.isEnabled(); - booleanPromise = elementFinder.isSelected(); - voidPromise = elementFinder.submit(); - voidPromise = elementFinder.clear(); - booleanPromise = elementFinder.isDisplayed(); - stringPromise = elementFinder.getOuterHtml(); - stringPromise = elementFinder.getInnerHtml(); - booleanPromise = elementFinder.isElementPresent(by.id('id')); - elementFinder = elementFinder.$('.class'); - var finders: protractor.ElementArrayFinder = elementFinder.$$('.class'); - elementFinder = elementFinder.evaluate('expression'); - booleanPromise = elementFinder.isPresent(); - - var webElement: webdriver.WebElement = elementFinder.getWebElement(); - finders = elementFinder.all(by.className('class')); - elementFinder = elementFinder.allowAnimations('abc'); - elementFinder = elementFinder.clone(); - elementFinder = elementFinder.element(by.id('id')); - - var b: boolean = elementFinder.isPending(); - var locator: webdriver.Locator = elementFinder.locator(); -} - -function TestElementArrayFinder() { - var elementArrayFinder: protractor.ElementArrayFinder = element.all(by.id('id')); - - var voidPromise: webdriver.promise.Promise; - var stringPromise: webdriver.promise.Promise; - var booleanPromise: webdriver.promise.Promise; - - elementArrayFinder.getId().then(function (id: webdriver.IWebElementId[]) { }); - voidPromise = elementArrayFinder.click(); - elementArrayFinder = elementArrayFinder.allowAnimations(true); - voidPromise = elementArrayFinder.sendKeys(protractor.Key.UP, protractor.Key.DOWN); - stringPromise = elementArrayFinder.getTagName(); - stringPromise = elementArrayFinder.getCssValue('display'); - stringPromise = elementArrayFinder.getAttribute('atribute'); - stringPromise = elementArrayFinder.getText(); - elementArrayFinder.getSize().then(function (size: webdriver.ISize[]) { }); - elementArrayFinder.getLocation().then(function (location: webdriver.ILocation[]) { }); - booleanPromise = elementArrayFinder.isEnabled(); - booleanPromise = elementArrayFinder.isSelected(); - voidPromise = elementArrayFinder.submit(); - voidPromise = elementArrayFinder.clear(); - booleanPromise = elementArrayFinder.isDisplayed(); - stringPromise = elementArrayFinder.getOuterHtml(); - stringPromise = elementArrayFinder.getInnerHtml(); - var finders: protractor.ElementArrayFinder = elementArrayFinder.$$('.class'); - elementArrayFinder = elementArrayFinder.evaluate('expression'); - - finders = elementArrayFinder.all(by.className('class')); - elementArrayFinder = elementArrayFinder.clone(); - - var b: boolean = elementArrayFinder.isPending(); - var locator: webdriver.Locator = elementArrayFinder.locator(); - - var findersArrayPromise: protractor.promise.Promise = elementArrayFinder.asElementFinders_(); - - var driverElementArray: webdriver.WebElement[] = elementArrayFinder.getWebElements(); - var elementFinder: protractor.ElementFinder = elementArrayFinder.get(42); - elementFinder = elementArrayFinder.first(); - elementFinder = elementArrayFinder.last(); - elementFinder = elementArrayFinder.toElementFinder_() - var numberPromise: protractor.promise.Promise = elementArrayFinder.count(); - elementArrayFinder.each(function(element: protractor.ElementFinder){ - // nothing - }); - - stringPromise = elementArrayFinder.map(function(element: protractor.ElementFinder, index: number){ - return 'abc'; - }); - - stringPromise = elementArrayFinder.map(function(element: protractor.ElementFinder, index: number): string { - return 'abc'; - }); - - stringPromise = elementArrayFinder.map>(function(element: protractor.ElementFinder, index: number): webdriver.promise.Promise { - return element.getText(); - }); - - elementArrayFinder = elementArrayFinder.filter(function(element: protractor.ElementFinder, index: number){ - return element.getText().then((text: string) => { - return text === "foo"; - }); - }); - elementArrayFinder.reduce(function (accumulator: string, element: protractor.ElementFinder) { - return element.getText().then((text: string) => { - return accumulator + ',' + text; - }); - }, '').then(function (result: string) { }); - elementArrayFinder.reduce(function(accumulator: string, element: protractor.ElementFinder, index: number, array: protractor.ElementFinder[]){ - return element.getText().then((text: string) => { - return accumulator + ',' + text; - }); - }, '').then(function (result: string) { }); - elementArrayFinder.then(function(underlyingElementFinders: protractor.ElementFinder[]){ - //nothing - }); -} - -// This function tests the locator strategies. -function TestLocatorStrategies() { - var ptor: protractor.Protractor = browser; - var webElement: webdriver.WebElement; - - protractor.By.addLocator('customLocator', 'script'); - protractor.By.addLocator('customLocator2', function(){ - // nothing - }); - - // Angular specific locators. - webElement = ptor.findElement(protractor.By.binding('binding')); - webElement = ptor.findElement(protractor.By.exactBinding('exactBinding')); - webElement = ptor.findElement(protractor.By.model('model')); - webElement = ptor.findElement(protractor.By.repeater('repeater')); - webElement = ptor.findElement(protractor.By.repeater('repeater').column(0)); - webElement = ptor.findElement(protractor.By.repeater('repeater').row(0)); - webElement = ptor.findElement(protractor.By.repeater('repeater').row(0).column(0)); - webElement = ptor.findElement(protractor.By.buttonText('buttonText')); - webElement = ptor.findElement(protractor.By.partialButtonText('partialButtonText')); - webElement = ptor.findElement(protractor.By.cssContainingText('cssSelector', 'search text')); - webElement = ptor.findElement(protractor.By.options('options')); - // One standard locator for good measure. - webElement = ptor.findElement(protractor.By.id('id')); - - var el: protractor.ElementFinder; - - // Angular specific locators. - el = element(by.binding('binding')); - el = element(by.exactBinding('exactBinding')); - el = element(by.model('model')); - el = element(by.repeater('repeater')); - el = element(by.repeater('repeater').column(0)); - el = element(by.repeater('repeater').row(0)); - el = element(by.repeater('repeater').row(0).column(0)); - el = element(by.buttonText('buttonText')); - el = element(by.partialButtonText('partialButtonText')); - el = element(by.cssContainingText('cssSelector', 'search text')); - el = element(by.options('options')); - // One standard locator for good measure. - el = element(by.id('id')); -} diff --git a/protractor/index.d.ts b/protractor/index.d.ts deleted file mode 100644 index 86f00898a1..0000000000 --- a/protractor/index.d.ts +++ /dev/null @@ -1,1849 +0,0 @@ -// Type definitions for Angular Protractor 1.5.0 -// Project: https://github.com/angular/protractor -// Definitions by: Bill Armstrong -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace protractor { - //region Wrapped webdriver Items - - class ActionSequence extends webdriver.ActionSequence {} - class Builder extends webdriver.Builder {} - class Capabilities extends webdriver.Capabilities {} - class Command extends webdriver.Command {} - class EventEmitter extends webdriver.EventEmitter {} - class Session extends webdriver.Session {} - class WebDriver extends webdriver.WebDriver {} - class WebElement extends webdriver.WebElement {} - class WebElementPromise extends webdriver.WebElementPromise { } - - var Browser: webdriver.IBrowser; - var Button: webdriver.IButton; - var Capability: webdriver.ICapability; - var CommandName: webdriver.ICommandName; - var Key: webdriver.IKey; - - namespace error { - class Error extends webdriver.error.Error {} - var ErrorCode: webdriver.error.IErrorCode; - } - - namespace logging { - class Preferences extends webdriver.logging.Preferences { } - class Entry extends webdriver.logging.Entry { } - - var Type: webdriver.logging.IType; - var Level: webdriver.logging.ILevelValues; - - function getLevel(nameOrValue: string): webdriver.logging.ILevel; - function getLevel(nameOrValue: number): webdriver.logging.ILevel; - } - - namespace promise { - class Thenable extends webdriver.promise.Thenable { } - class Promise extends webdriver.promise.Promise { } - class Deferred extends webdriver.promise.Deferred { } - class ControlFlow extends webdriver.promise.ControlFlow { } - class CancellationError extends webdriver.promise.CancellationError { } - - /** - * Given an array of promises, will return a promise that will be fulfilled - * with the fulfillment values of the input array's values. If any of the - * input array's promises are rejected, the returned promise will be rejected - * with the same reason. - * - * @param {!Array.<(T|!webdriver.promise.Promise.)>} arr An array of - * promises to wait on. - * @return {!webdriver.promise.Promise.>} A promise that is - * fulfilled with an array containing the fulfilled values of the - * input array, or rejected with the same reason as the first - * rejected value. - * @template T - */ - function all(arr: webdriver.promise.Promise[]): webdriver.promise.Promise; - - /** - * Invokes the appropriate callback function as soon as a promised - * {@code value} is resolved. This function is similar to - * {@link webdriver.promise.when}, except it does not return a new promise. - * @param {*} value The value to observe. - * @param {Function} callback The function to call when the value is - * resolved successfully. - * @param {Function=} opt_errback The function to call when the value is - * rejected. - */ - function asap(value: any, callback: Function, opt_errback?: Function): void; - - /** - * @return {!webdriver.promise.ControlFlow} The currently active control flow. - */ - function controlFlow(): webdriver.promise.ControlFlow; - - /** - * Creates a new control flow. The provided callback will be invoked as the - * first task within the new flow, with the flow as its sole argument. Returns - * a promise that resolves to the callback result. - * @param {function(!webdriver.promise.ControlFlow)} callback The entry point - * to the newly created flow. - * @return {!webdriver.promise.Promise} A promise that resolves to the callback - * result. - */ - function createFlow(callback: (flow: webdriver.promise.ControlFlow) => R): webdriver.promise.Promise; - - /** - * Determines whether a {@code value} should be treated as a promise. - * Any object whose "then" property is a function will be considered a promise. - * - * @param {*} value The value to test. - * @return {boolean} Whether the value is a promise. - */ - function isPromise(value: any): boolean; - - /** - * Tests is a function is a generator. - * @param {!Function} fn The function to test. - * @return {boolean} Whether the function is a generator. - */ - function isGenerator(fn: Function): boolean; - - /** - * Creates a promise that will be resolved at a set time in the future. - * @param {number} ms The amount of time, in milliseconds, to wait before - * resolving the promise. - * @return {!webdriver.promise.Promise} The promise. - */ - function delayed(ms: number): webdriver.promise.Promise; - - /** - * Calls a function for each element in an array, and if the function returns - * true adds the element to a new array. - * - *

If the return value of the filter function is a promise, this function - * will wait for it to be fulfilled before determining whether to insert the - * element into the new array. - * - *

If the filter function throws or returns a rejected promise, the promise - * returned by this function will be rejected with the same reason. Only the - * first failure will be reported; all subsequent errors will be silently - * ignored. - * - * @param {!(Array.|webdriver.promise.Promise.>)} arr The - * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array.): ( - * boolean|webdriver.promise.Promise.)} fn The function - * to call for each element in the array. - * @param {SELF=} opt_self The object to be used as the value of 'this' within - * {@code fn}. - * @template TYPE, SELF - */ - function filter(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise; - function filter(arr: webdriver.promise.Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise - - /** - * Creates a new deferred object. - * @return {!webdriver.promise.Deferred} The new deferred object. - */ - function defer(): webdriver.promise.Deferred; - - /** - * Creates a promise that has been resolved with the given value. - * @param {*=} opt_value The resolved value. - * @return {!webdriver.promise.Promise} The resolved promise. - */ - function fulfilled(opt_value?: T): webdriver.promise.Promise; - - /** - * Calls a function for each element in an array and inserts the result into a - * new array, which is used as the fulfillment value of the promise returned - * by this function. - * - *

If the return value of the mapping function is a promise, this function - * will wait for it to be fulfilled before inserting it into the new array. - * - *

If the mapping function throws or returns a rejected promise, the - * promise returned by this function will be rejected with the same reason. - * Only the first failure will be reported; all subsequent errors will be - * silently ignored. - * - * @param {!(Array.|webdriver.promise.Promise.>)} arr The - * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array.): ?} fn The - * function to call for each element in the array. This function should - * expect three arguments (the element, the index, and the array itself. - * @param {SELF=} opt_self The object to be used as the value of 'this' within - * {@code fn}. - * @template TYPE, SELF - */ - function map(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise - function map(arr: webdriver.promise.Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise - - /** - * Creates a promise that has been rejected with the given reason. - * @param {*=} opt_reason The rejection reason; may be any value, but is - * usually an Error or a string. - * @return {!webdriver.promise.Promise} The rejected promise. - */ - function rejected(opt_reason?: any): webdriver.promise.Promise; - - /** - * Wraps a function that is assumed to be a node-style callback as its final - * argument. This callback takes two arguments: an error value (which will be - * null if the call succeeded), and the success value as the second argument. - * If the call fails, the returned promise will be rejected, otherwise it will - * be resolved with the result. - * @param {!Function} fn The function to wrap. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * result of the provided function's callback. - */ - function checkedNodeCall(fn: Function, ...var_args: any[]): webdriver.promise.Promise; - - /** - * Consumes a {@code GeneratorFunction}. Each time the generator yields a - * promise, this function will wait for it to be fulfilled before feeding the - * fulfilled value back into {@code next}. Likewise, if a yielded promise is - * rejected, the rejection error will be passed to {@code throw}. - * - *

Example 1: the Fibonacci Sequence. - *


-         * webdriver.promise.consume(function* fibonacci() {
-         *   var n1 = 1, n2 = 1;
-         *   for (var i = 0; i < 4; ++i) {
-         *     var tmp = yield n1 + n2;
-         *     n1 = n2;
-         *     n2 = tmp;
-         *   }
-         *   return n1 + n2;
-         * }).then(function(result) {
-         *   console.log(result);  // 13
-         * });
-         * 
- * - *

Example 2: a generator that throws. - *


-         * webdriver.promise.consume(function* () {
-         *   yield webdriver.promise.delayed(250).then(function() {
-         *     throw Error('boom');
-         *   });
-         * }).thenCatch(function(e) {
-         *   console.log(e.toString());  // Error: boom
-         * });
-         * 
- * - * @param {!Function} generatorFn The generator function to execute. - * @param {Object=} opt_self The object to use as "this" when invoking the - * initial generator. - * @param {...*} var_args Any arguments to pass to the initial generator. - * @return {!webdriver.promise.Promise.} A promise that will resolve to the - * generator's final result. - * @throws {TypeError} If the given function is not a generator. - */ - function consume(generatorFn: Function, opt_self?: any, ...var_args: any[]): webdriver.promise.Promise; - - /** - * Registers an observer on a promised {@code value}, returning a new promise - * that will be resolved when the value is. If {@code value} is not a promise, - * then the return promise will be immediately resolved. - * @param {*} value The value to observe. - * @param {Function=} opt_callback The function to call when the value is - * resolved successfully. - * @param {Function=} opt_errback The function to call when the value is - * rejected. - * @return {!webdriver.promise.Promise} A new promise. - */ - function when(value: T, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise; - function when(value: webdriver.promise.Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise; - - /** - * Returns a promise that will be resolved with the input value in a - * fully-resolved state. If the value is an array, each element will be fully - * resolved. Likewise, if the value is an object, all keys will be fully - * resolved. In both cases, all nested arrays and objects will also be - * fully resolved. All fields are resolved in place; the returned promise will - * resolve on {@code value} and not a copy. - * - * Warning: This function makes no checks against objects that contain - * cyclical references: - * - * var value = {}; - * value['self'] = value; - * webdriver.promise.fullyResolved(value); // Stack overflow. - * - * @param {*} value The value to fully resolve. - * @return {!webdriver.promise.Promise} A promise for a fully resolved version - * of the input value. - */ - function fullyResolved(value: any): webdriver.promise.Promise; - - /** - * Changes the default flow to use when no others are active. - * @param {!webdriver.promise.ControlFlow} flow The new default flow. - * @throws {Error} If the default flow is not currently active. - */ - function setDefaultFlow(flow: webdriver.promise.ControlFlow): void; - } - - namespace stacktrace { - class Frame extends webdriver.stacktrace.Frame { } - class Snapshot extends webdriver.stacktrace.Snapshot { } - - /** - * Formats an error's stack trace. - * @param {!(Error|goog.testing.JsUnitException)} error The error to format. - * @return {!(Error|goog.testing.JsUnitException)} The formatted error. - */ - function format(error: any): any; - - /** - * Gets the native stack trace if available otherwise follows the call chain. - * The generated trace will exclude all frames up to and including the call to - * this function. - * @return {!Array.} The frames of the stack trace. - */ - function get(): webdriver.stacktrace.Frame[]; - - /** - * Whether the current browser supports stack traces. - * - * @type {boolean} - * @const - */ - var BROWSER_SUPPORTED: boolean; - } - - namespace until { - class Condition extends webdriver.until.Condition { } - - /** - * Creates a condition that will wait until the input driver is able to switch - * to the designated frame. The target frame may be specified as: - *
    - *
  1. A numeric index into {@code window.frames} for the currently selected - * frame. - *
  2. A {@link webdriver.WebElement}, which must reference a FRAME or IFRAME - * element on the current page. - *
  3. A locator which may be used to first locate a FRAME or IFRAME on the - * current page before attempting to switch to it. - *
- * - *

Upon successful resolution of this condition, the driver will be left - * focused on the new frame. - * - * @param {!(number|webdriver.WebElement| - * webdriver.Locator|webdriver.By.Hash| - * function(!webdriver.WebDriver): !webdriver.WebElement)} frame - * The frame identifier. - * @return {!until.Condition.} A new condition. - */ - function ableToSwitchToFrame(frame: number): webdriver.until.Condition; - function ableToSwitchToFrame(frame: webdriver.IWebElement): webdriver.until.Condition; - function ableToSwitchToFrame(frame: webdriver.Locator): webdriver.until.Condition; - function ableToSwitchToFrame(frame: (webdriver: webdriver.WebDriver) => webdriver.IWebElement): webdriver.until.Condition; - function ableToSwitchToFrame(frame: any): webdriver.until.Condition; - - /** - * Creates a condition that waits for an alert to be opened. Upon success, the - * returned promise will be fulfilled with the handle for the opened alert. - * - * @return {!until.Condition.} The new condition. - */ - function alertIsPresent(): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to be disabled. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isEnabled - */ - function elementIsDisabled(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to be enabled. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isEnabled - */ - function elementIsEnabled(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to be deselected. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isSelected - */ - function elementIsNotSelected(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to be in the DOM, - * yet not visible to the user. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isDisplayed - */ - function elementIsNotVisible(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to be selected. - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isSelected - */ - function elementIsSelected(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to become visible. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isDisplayed - */ - function elementIsVisible(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will loop until an element is - * {@link webdriver.WebDriver#findElement found} with the given locator. - * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * to use. - * @return {!until.Condition.} The new condition. - */ - function elementLocated(locator: webdriver.Locator): webdriver.until.Condition; - function elementLocated(locator: any): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element's - * {@link webdriver.WebDriver#getText visible text} to contain the given - * substring. - * - * @param {!webdriver.WebElement} element The element to test. - * @param {string} substr The substring to search for. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#getText - */ - function elementTextContains(element: webdriver.IWebElement, substr: string): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element's - * {@link webdriver.WebDriver#getText visible text} to match the given - * {@code text} exactly. - * - * @param {!webdriver.WebElement} element The element to test. - * @param {string} text The expected text. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#getText - */ - function elementTextIs(element: webdriver.IWebElement, text: string): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element's - * {@link webdriver.WebDriver#getText visible text} to match a regular - * expression. - * - * @param {!webdriver.WebElement} element The element to test. - * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#getText - */ - function elementTextMatches(element: webdriver.IWebElement, regex: RegExp): webdriver.until.Condition; - - /** - * Creates a condition that will loop until at least one element is - * {@link webdriver.WebDriver#findElement found} with the given locator. - * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * to use. - * @return {!until.Condition.>} The new - * condition. - */ - function elementsLocated(locator: webdriver.Locator): webdriver.until.Condition; - function elementsLocated(locator: any): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to become stale. An - * element is considered stale once it is removed from the DOM, or a new page - * has loaded. - * - * @param {!webdriver.WebElement} element The element that should become stale. - * @return {!until.Condition.} The new condition. - */ - function stalenessOf(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the current page's title to contain - * the given substring. - * - * @param {string} substr The substring that should be present in the page - * title. - * @return {!until.Condition.} The new condition. - */ - function titleContains(substr: string): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the current page's title to match the - * given value. - * - * @param {string} title The expected page title. - * @return {!until.Condition.} The new condition. - */ - function titleIs(title: string): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the current page's title to match the - * given regular expression. - * - * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition.} The new condition. - */ - function titleMatches(regex: RegExp): webdriver.until.Condition; - } - - namespace ExpectedConditions { - /** - * Negates the result of a promise. - * - * @param {webdriver.until.Condition} expectedCondition - * @return {!webdriver.until.Condition} An expected condition that returns the negated value. - */ - function not(expectedCondition: webdriver.until.Condition): webdriver.until.Condition; - - /** - * Chain a number of expected conditions using logical_and, short circuiting at the - * first expected condition that evaluates to false. - * - * @param {...webdriver.until.Condition[]} fns An array of expected conditions to 'and' together. - * @return {!webdriver.until.Condition} An expected condition that returns a promise which evaluates - * to the result of the logical and. - */ - function and(...fns: webdriver.until.Condition[]): webdriver.until.Condition; - - /** - * Chain a number of expected conditions using logical_or, short circuiting at the - * first expected condition that evaluates to true. - * - * @param {...webdriver.until.Condition[]} fns An array of expected conditions to 'or' together. - * @return {!webdriver.until.Condition} An expected condition that returns a promise which - * evaluates to the result of the logical or. - */ - function or(...fns: webdriver.until.Condition[]): webdriver.until.Condition; - - /** - * Expect an alert to be present. - * - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether an alert is present. - */ - function alertIsPresent(): webdriver.until.Condition; - - /** - * An Expectation for checking an element is visible and enabled such that you can click it. - * - * @param {ElementFinder} element The element to check - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the element is clickable. - */ - function elementToBeClickable(element: ElementFinder): webdriver.until.Condition; - - /** - * An expectation for checking if the given text is present in the element. - * Returns false if the elementFinder does not find an element. - * - * @param {ElementFinder} element The element to check - * @param {string} text The text to verify against - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the text is present in the element. - */ - function textToBePresentInElement(element: ElementFinder, text: string): webdriver.until.Condition; - - /** - * An expectation for checking if the given text is present in the element’s value. - * Returns false if the elementFinder does not find an element. - * - * @param {ElementFinder} element The element to check - * @param {string} text The text to verify against - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the text is present in the element's value. - */ - function textToBePresentInElementValue( - element: ElementFinder, text: string - ): webdriver.until.Condition; - - /** - * An expectation for checking that the title contains a case-sensitive substring. - * - * @param {string} title The fragment of title expected - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the title contains the string. - */ - function titleContains(title: string): webdriver.until.Condition; - - /** - * An expectation for checking the title of a page. - * - * @param {string} title The expected title, which must be an exact match. - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the title equals the string. - */ - function titleIs(title: string): webdriver.until.Condition; - - /** - * An expectation for checking that an element is present on the DOM of a page. This does not necessarily - * mean that the element is visible. This is the opposite of 'stalenessOf'. - * - * @param {ElementFinder} elementFinder The element to check - * @return {!webdriver.until.Condition} An expected condition that returns a promise - * representing whether the element is present. - */ - function presenceOf(element: ElementFinder): webdriver.until.Condition; - - /** - * An expectation for checking that an element is not attached to the DOM of a page. - * This is the opposite of 'presenceOf'. - * - * @param {ElementFinder} elementFinder The element to check - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the element is stale. - */ - function stalenessOf(element: ElementFinder): webdriver.until.Condition; - - /** - * An expectation for checking that an element is present on the DOM of a page and visible. - * Visibility means that the element is not only displayed but also has a height and width that is - * greater than 0. This is the opposite of 'invisibilityOf'. - * - * @param {ElementFinder} elementFinder The element to check - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the element is visible. - */ - function visibilityOf(element: ElementFinder): webdriver.until.Condition; - - /** - * An expectation for checking that an element is present on the DOM of a page. This does not necessarily - * mean that the element is visible. This is the opposite of 'stalenessOf'. - * - * @param {ElementFinder} elementFinder The element to check - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the element is invisible. - */ - function invisibilityOf(element: ElementFinder): webdriver.until.Condition; - - /** - * An expectation for checking the selection is selected. - * - * @param {ElementFinder} elementFinder The element to check - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the element is selected. - */ - function elementToBeSelected(element: ElementFinder): webdriver.until.Condition; - } - - //endregion - - /** - * Use as: element(locator) - * - * The ElementFinder can be treated as a WebElement for most purposes, in - * particular, you may perform actions (i.e. click, getText) on them as you - * would a WebElement. ElementFinders extend Promise, and once an action - * is performed on an ElementFinder, the latest result from the chain can be - * accessed using then. Unlike a WebElement, an ElementFinder will wait for - * angular to settle before performing finds or actions. - * - * ElementFinder can be used to build a chain of locators that is used to find - * an element. An ElementFinder does not actually attempt to find the element - * until an action is called, which means they can be set up in helper files - * before the page is available. - * - * @param {webdriver.Locator} locator An element locator. - * @return {ElementFinder} - */ - interface Element { - (locator: webdriver.Locator): ElementFinder; - - /** - * ElementArrayFinder is used for operations on an array of elements (as opposed - * to a single element). - * - * @param {webdriver.Locator} locator An element locator. - * @return {ElementArrayFinder} - */ - all(locator: webdriver.Locator): ElementArrayFinder; - } - - interface ElementFinder extends webdriver.IWebElement, webdriver.promise.IThenable { - /** - * Calls to element may be chained to find elements within a parent. - * - * @alias element(locator).element(locator) - * @view - *

- *
- * Child text - *
{{person.phone}}
- *
- *
- * - * @example - * // Chain 2 element calls. - * var child = element(by.css('.parent')). - * element(by.css('.child')); - * expect(child.getText()).toBe('Child text\n555-123-4567'); - * - * // Chain 3 element calls. - * var triple = element(by.css('.parent')). - * element(by.css('.child')). - * element(by.binding('person.phone')); - * expect(triple.getText()).toBe('555-123-4567'); - * - * @param {webdriver.Locator} subLocator - * @return {ElementFinder} - */ - element(subLocator: webdriver.Locator): ElementFinder; - - /** - * Calls to element may be chained to find an array of elements within a parent. - * - * @alias element(locator).all(locator) - * @view - *
- *
    - *
  • First
  • - *
  • Second
  • - *
  • Third
  • - *
- *
- * - * @example - * var items = element(by.css('.parent')).all(by.tagName('li')) - * - * @param {webdriver.Locator} subLocator - * @return {ElementArrayFinder} - */ - all(subLocator: webdriver.Locator): ElementArrayFinder; - - /** - * Shortcut for querying the document directly with css. - * - * @alias $(cssSelector) - * @view - *
- * First - * Second - *
- * - * @example - * var item = $('.count .two'); - * expect(item.getText()).toBe('Second'); - * - * @param {string} selector A css selector - * @return {ElementFinder} which identifies the located - * {@link webdriver.WebElement} - */ - $(selector: string): ElementFinder; - - /** - * Shortcut for querying the document directly with css. - * - * @alias $$(cssSelector) - * @view - *
- * First - * Second - *
- * - * @example - * // The following protractor expressions are equivalent. - * var list = element.all(by.css('.count span')); - * expect(list.count()).toBe(2); - * - * list = $$('.count span'); - * expect(list.count()).toBe(2); - * expect(list.get(0).getText()).toBe('First'); - * expect(list.get(1).getText()).toBe('Second'); - * - * @param {string} selector a css selector - * @return {ElementArrayFinder} which identifies the - * array of the located {@link webdriver.WebElement}s. - */ - $$(selector: string): ElementArrayFinder; - - /** - * Determine whether the element is present on the page. - * - * @view - * {{person.name}} - * - * @example - * // Element exists. - * expect(element(by.binding('person.name')).isPresent()).toBe(true); - * - * // Element not present. - * expect(element(by.binding('notPresent')).isPresent()).toBe(false); - * - * @return {ElementFinder} which resolves to whether - * the element is present on the page. - */ - isPresent(): webdriver.promise.Promise; - - /** - * Override for WebElement.prototype.isElementPresent so that protractor waits - * for Angular to settle before making the check. - * - * @see ElementFinder.isPresent - * - * @param {webdriver.Locator} subLocator Locator for element to look for. - * @return {ElementFinder} which resolves to whether - * the element is present on the page. - */ - isElementPresent(subLocator: webdriver.Locator): webdriver.promise.Promise; - - /** - * @see ElementArrayFinder.prototype.locator - * - * @return {webdriver.Locator} - */ - locator(): webdriver.Locator; - - /** - * Returns the WebElement represented by this ElementFinder. - * Throws the WebDriver error if the element doesn't exist. - * - * @example - * The following three expressions are equivalent. - * element(by.css('.parent')).getWebElement(); - * browser.waitForAngular(); browser.driver.findElement(by.css('.parent')); - * browser.findElement(by.css('.parent')); - * - * @alias element(locator).getWebElement() - * @return {webdriver.WebElement} - */ - getWebElement(): webdriver.WebElement; - - /** - * Evaluates the input as if it were on the scope of the current element. - * @see ElementArrayFinder.evaluate - * - * @param {string} expression - * - * @return {ElementFinder} which resolves to the evaluated expression. - */ - evaluate(expression: string): ElementFinder; - - /** - * @see ElementArrayFinder.prototype.allowAnimations. - * @param {string} value - * - * @return {ElementFinder} which resolves to whether animation is allowed. - */ - allowAnimations(value: string): ElementFinder; - - /** - * Create a shallow copy of ElementFinder. - * - * @return {!ElementFinder} A shallow copy of this. - */ - clone(): ElementFinder; - } - - interface ElementArrayFinder extends webdriver.promise.IThenable { - /** - * Returns the elements as an array of WebElements. - */ - getWebElements(): webdriver.WebElement[]; - - - /** - * Get an element within the ElementArrayFinder by index. The index starts at 0. - * Negative indices are wrapped (i.e. -i means ith element from last) - * This does not actually retrieve the underlying element. - * - * @alias element.all(locator).get(index) - * @view - *
    - *
  • First
  • - *
  • Second
  • - *
  • Third
  • - *
- * - * @example - * var list = element.all(by.css('.items li')); - * expect(list.get(0).getText()).toBe('First'); - * expect(list.get(1).getText()).toBe('Second'); - * - * @param {number} index Element index. - * @return {ElementFinder} finder representing element at the given index. - */ - get(index: number): ElementFinder; - - /** - * Get the first matching element for the ElementArrayFinder. This does not - * actually retrieve the underlying element. - * - * @alias element.all(locator).first() - * @view - *
    - *
  • First
  • - *
  • Second
  • - *
  • Third
  • - *
- * - * @example - * var first = element.all(by.css('.items li')).first(); - * expect(first.getText()).toBe('First'); - * - * @return {ElementFinder} finder representing the first matching element - */ - first(): ElementFinder; - - /** - * Get the last matching element for the ElementArrayFinder. This does not - * actually retrieve the underlying element. - * - * @alias element.all(locator).last() - * @view - *
    - *
  • First
  • - *
  • Second
  • - *
  • Third
  • - *
- * - * @example - * var last = element.all(by.css('.items li')).last(); - * expect(last.getText()).toBe('Third'); - * - * @return {ElementFinder} finder representing the last matching element - */ - last(): ElementFinder; - - /** - * Count the number of elements represented by the ElementArrayFinder. - * - * @alias element.all(locator).count() - * @view - *
    - *
  • First
  • - *
  • Second
  • - *
  • Third
  • - *
- * - * @example - * var list = element.all(by.css('.items li')); - * expect(list.count()).toBe(3); - * - * @return {!webdriver.promise.Promise} A promise which resolves to the - * number of elements matching the locator. - */ - count(): webdriver.promise.Promise; - - /** - * Calls the input function on each ElementFinder represented by the ElementArrayFinder. - * - * @alias element.all(locator).each(eachFunction) - * @view - *
    - *
  • First
  • - *
  • Second
  • - *
  • Third
  • - *
- * - * @example - * element.all(by.css('.items li')).each(function(element) { - * // Will print First, Second, Third. - * element.getText().then(console.log); - * }); - * - * @param {function(ElementFinder)} fn Input function - */ - each(fn: (element: ElementFinder, index: number) => void): void; - - /** - * Apply a map function to each element within the ElementArrayFinder. The - * callback receives the ElementFinder as the first argument and the index as - * a second arg. - * - * @alias element.all(locator).map(mapFunction) - * @view - *
    - *
  • First
  • - *
  • Second
  • - *
  • Third
  • - *
- * - * @example - * var items = element.all(by.css('.items li')).map(function(elm, index) { - * return { - * index: index, - * text: elm.getText(), - * class: elm.getAttribute('class') - * }; - * }); - * expect(items).toEqual([ - * {index: 0, text: 'First', class: 'one'}, - * {index: 1, text: 'Second', class: 'two'}, - * {index: 2, text: 'Third', class: 'three'} - * ]); - * - * @param {function(ElementFinder, number)} mapFn Map function that - * will be applied to each element. - * @return {!webdriver.promise.Promise} A promise that resolves to an array - * of values returned by the map function. - */ - map(mapFn: (element: ElementFinder, index: number) => T): webdriver.promise.Promise; - map(mapFn: (element: ElementFinder, index: number) => T2): webdriver.promise.Promise; - - /** - * Apply a filter function to each element within the ElementArrayFinder. Returns - * a new ElementArrayFinder with all elements that pass the filter function. The - * filter function receives the ElementFinder as the first argument - * and the index as a second arg. - * This does not actually retrieve the underlying list of elements, so it can - * be used in page objects. - * - * @alias element.all(locator).filter(filterFn) - * @view - *
    - *
  • First
  • - *
  • Second
  • - *
  • Third
  • - *
- * - * @example - * element.all(by.css('.items li')).filter(function(elem, index) { - * return elem.getText().then(function(text) { - * return text === 'Third'; - * }); - * }).then(function(filteredElements) { - * filteredElements[0].click(); - * }); - * - * @param {function(ElementFinder, number): webdriver.WebElement.Promise} filterFn - * Filter function that will test if an element should be returned. - * filterFn can either return a boolean or a promise that resolves to a boolean. - * @return {!ElementArrayFinder} A ElementArrayFinder that represents an array - * of element that satisfy the filter function. - */ - filter(filterFn: (element: ElementFinder, index: number) => any): ElementArrayFinder; - - /** - * Apply a reduce function against an accumulator and every element found - * using the locator (from left-to-right). The reduce function has to reduce - * every element into a single value (the accumulator). Returns promise of - * the accumulator. The reduce function receives the accumulator, current - * ElementFinder, the index, and the entire array of ElementFinders, - * respectively. - * - * @alias element.all(locator).reduce(reduceFn) - * @view - *
    - *
  • First
  • - *
  • Second
  • - *
  • Third
  • - *
- * - * @example - * var value = element.all(by.css('.items li')).reduce(function(acc, elem) { - * return elem.getText().then(function(text) { - * return acc + text + ' '; - * }); - * }); - * - * expect(value).toEqual('First Second Third '); - * - * @param {function(number, ElementFinder, number, Array.)} - * reduceFn Reduce function that reduces every element into a single value. - * @param {*} initialValue Initial value of the accumulator. - * @return {!webdriver.promise.Promise} A promise that resolves to the final - * value of the accumulator. - */ - reduce(reduceFn: (acc: T, element: ElementFinder, index: number, arr: ElementFinder[]) => webdriver.promise.Promise, initialValue: T): webdriver.promise.Promise; - reduce(reduceFn: (acc: T, element: ElementFinder, index: number, arr: ElementFinder[]) => T, initialValue: T): webdriver.promise.Promise; - - /** - * Represents the ElementArrayFinder as an array of ElementFinders. - * - * @return {Array.} Return a promise, which resolves to a list - * of ElementFinders specified by the locator. - */ - asElementFinders_(): webdriver.promise.Promise; - - /** - * Create a shallow copy of ElementArrayFinder. - * - * @return {!ElementArrayFinder} A shallow copy of this. - */ - clone(): ElementArrayFinder; - - /** - * Calls to ElementArrayFinder may be chained to find an array of elements - * using the current elements in this ElementArrayFinder as the starting point. - * This function returns a new ElementArrayFinder which would contain the - * children elements found (and could also be empty). - * - * @alias element.all(locator).all(locator) - * @view - *
- *
    - *
  • 1a
  • - *
  • 1b
  • - *
- *
- *
- *
    - *
  • 2a
  • - *
  • 2b
  • - *
- *
- * - * @example - * var foo = element.all(by.css('.parent')).all(by.css('.foo')) - * expect(foo.getText()).toEqual(['1a', '2a']) - * var baz = element.all(by.css('.parent')).all(by.css('.baz')) - * expect(baz.getText()).toEqual(['1b']) - * var nonexistent = element.all(by.css('.parent')).all(by.css('.NONEXISTENT')) - * expect(nonexistent.getText()).toEqual(['']) - * - * @param {webdriver.Locator} subLocator - * @return {ElementArrayFinder} - */ - all(locator: webdriver.Locator): ElementArrayFinder; - - /** - * Shorthand function for finding arrays of elements by css. - * - * @type {function(string): ElementArrayFinder} - */ - $$(selector: string): ElementArrayFinder; - - /** - * Returns an ElementFinder representation of ElementArrayFinder. It ensures - * that the ElementArrayFinder resolves to one and only one underlying element. - * - * @return {ElementFinder} An ElementFinder representation - * @private - */ - toElementFinder_(): ElementFinder; - - /** - * Returns the most relevant locator. - * - * @example - * $('#ID1').locator() // returns by.css('#ID1') - * $('#ID1').$('#ID2').locator() // returns by.css('#ID2') - * $$('#ID1').filter(filterFn).get(0).click().locator() // returns by.css('#ID1') - * - * @return {webdriver.Locator} - */ - locator(): webdriver.Locator; - - /** - * Evaluates the input as if it were on the scope of the current underlying - * elements. - * - * @view - * {{variableInScope}} - * - * @example - * var value = element(by.id('foo')).evaluate('variableInScope'); - * - * @param {string} expression - * - * @return {ElementArrayFinder} which resolves to the - * evaluated expression for each underlying element. - * The result will be resolved as in - * {@link webdriver.WebDriver.executeScript}. In summary - primitives will - * be resolved as is, functions will be converted to string, and elements - * will be returned as a WebElement. - */ - evaluate(expression: string): ElementArrayFinder; - - /** - * Determine if animation is allowed on the current underlying elements. - * @param {string} value - * - * @example - * // Turns off ng-animate animations for all elements in the - * element(by.css('body')).allowAnimations(false); - * - * @return {ElementArrayFinder} which resolves to whether animation is allowed. - */ - allowAnimations(value: boolean): ElementArrayFinder; - - /** - * Schedules a command to click on this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * the click command has completed. - */ - click(): webdriver.promise.Promise; - - /** - * Schedules a command to type a sequence on the DOM element represented by this - * instance. - *

- * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is - * processed in the keysequence, that key state is toggled until one of the - * following occurs: - *

    - *
  • The modifier key is encountered again in the sequence. At this point the - * state of the key is toggled (along with the appropriate keyup/down events). - *
  • - *
  • The {@code webdriver.Key.NULL} key is encountered in the sequence. When - * this key is encountered, all modifier keys current in the down state are - * released (with accompanying keyup events). The NULL key can be used to - * simulate common keyboard shortcuts: - * - * element.sendKeys("text was", - * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, - * "now text is"); - * // Alternatively: - * element.sendKeys("text was", - * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), - * "now text is"); - *
  • - *
  • The end of the keysequence is encountered. When there are no more keys - * to type, all depressed modifier keys are released (with accompanying keyup - * events). - *
  • - *
- * Note: On browsers where native keyboard events are not yet - * supported (e.g. Firefox on OS X), key events will be synthesized. Special - * punctionation keys will be synthesized according to a standard QWERTY en-us - * keyboard layout. - * - * @param {...string} var_args The sequence of keys to - * type. All arguments will be joined into a single sequence (var_args is - * permitted for convenience). - * @return {!webdriver.promise.Promise} A promise that will be resolved when all - * keys have been typed. - */ - sendKeys(...var_args: string[]): webdriver.promise.Promise; - - /** - * Schedules a command to query for the tag/node name of this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * element's tag name. - */ - getTagName(): webdriver.promise.Promise; - - /** - * Schedules a command to query for the computed style of the element - * represented by this instance. If the element inherits the named style from - * its parent, the parent will be queried for its value. Where possible, color - * values will be converted to their hex representation (e.g. #00ff00 instead of - * rgb(0, 255, 0)). - *

- * Warning: the value returned will be as the browser interprets it, so - * it may be tricky to form a proper assertion. - * - * @param {string} cssStyleProperty The name of the CSS style property to look - * up. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * requested CSS value. - */ - getCssValue(cssStyleProperty: string): webdriver.promise.Promise; - - /** - * Schedules a command to query for the value of the given attribute of the - * element. Will return the current value even if it has been modified after the - * page has been loaded. More exactly, this method will return the value of the - * given attribute, unless that attribute is not present, in which case the - * value of the property with the same name is returned. If neither value is - * set, null is returned. The "style" attribute is converted as best can be to a - * text representation with a trailing semi-colon. The following are deemed to - * be "boolean" attributes and will be returned as thus: - * - *

async, autofocus, autoplay, checked, compact, complete, controls, declare, - * defaultchecked, defaultselected, defer, disabled, draggable, ended, - * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, - * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, - * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, - * selected, spellcheck, truespeed, willvalidate - * - *

Finally, the following commonly mis-capitalized attribute/property names - * are evaluated as expected: - *

    - *
  • "class" - *
  • "readonly" - *
- * @param {string} attributeName The name of the attribute to query. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * attribute's value. - */ - getAttribute(attributeName: string): webdriver.promise.Promise; - - /** - * Get the visible (i.e. not hidden by CSS) innerText of this element, including - * sub-elements, without any leading or trailing whitespace. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * element's visible text. - */ - getText(): webdriver.promise.Promise; - - /** - * Schedules a command to compute the size of this element's bounding box, in - * pixels. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * element's size as a {@code {width:number, height:number}} object. - */ - getSize(): webdriver.promise.Promise; - - /** - * Schedules a command to compute the location of this element in page space. - * @return {!webdriver.promise.Promise} A promise that will be resolved to the - * element's location as a {@code {x:number, y:number}} object. - */ - getLocation(): webdriver.promise.Promise; - - /** - * Schedules a command to query whether the DOM element represented by this - * instance is enabled, as dicted by the {@code disabled} attribute. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether this element is currently enabled. - */ - isEnabled(): webdriver.promise.Promise; - - /** - * Schedules a command to query whether this element is selected. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether this element is currently selected. - */ - isSelected(): webdriver.promise.Promise; - - /** - * Schedules a command to submit the form containing this element (or this - * element if it is a FORM element). This command is a no-op if the element is - * not contained in a form. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * the form has been submitted. - */ - submit(): webdriver.promise.Promise; - - /** - * Schedules a command to clear the {@code value} of this element. This command - * has no effect if the underlying DOM element is neither a text INPUT element - * nor a TEXTAREA element. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * the element has been cleared. - */ - clear(): webdriver.promise.Promise; - - /** - * Schedules a command to test whether this element is currently displayed. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether this element is currently visible on the page. - */ - isDisplayed(): webdriver.promise.Promise; - - /** - * Schedules a command to retrieve the outer HTML of this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * the element's outer HTML. - */ - getOuterHtml(): webdriver.promise.Promise; - - /** - * @return {!webdriver.promise.Promise.} A promise - * that resolves to this element's JSON representation as defined by the - * WebDriver wire protocol. - * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol - */ - getId(): webdriver.promise.Promise - - /** - * Schedules a command to retrieve the inner HTML of this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * element's inner HTML. - */ - getInnerHtml(): webdriver.promise.Promise; - } - - interface LocatorWithColumn extends webdriver.Locator { - column(index: number): webdriver.Locator; - column(name: string): webdriver.Locator; - } - - interface RepeaterLocator extends LocatorWithColumn { - row(index: number): LocatorWithColumn; - } - - interface IProtractorLocatorStrategy { - /** - * webdriver's By is an enum of locator functions, so we must set it to - * a prototype before inheriting from it. - */ - className: typeof webdriver.By.className; - css: typeof webdriver.By.css; - id: typeof webdriver.By.id; - linkText: typeof webdriver.By.linkText; - js: typeof webdriver.By.js; - name: typeof webdriver.By.name; - partialLinkText: typeof webdriver.By.partialLinkText; - tagName: typeof webdriver.By.tagName; - xpath: typeof webdriver.By.xpath; - - /** - * Add a locator to this instance of ProtractorBy. This locator can then be - * used with element(by.locatorName(args)). - * - * @view - * - * - * @example - * // Add the custom locator. - * by.addLocator('buttonTextSimple', - * function(buttonText, opt_parentElement, opt_rootSelector) { - * // This function will be serialized as a string and will execute in the - * // browser. The first argument is the text for the button. The second - * // argument is the parent element, if any. - * var using = opt_parentElement, - * buttons = using.querySelectorAll('button'); - * - * // Return an array of buttons with the text. - * return Array.prototype.filter.call(buttons, function(button) { - * return button.textContent === buttonText; - * }); - * }); - * - * // Use the custom locator. - * element(by.buttonTextSimple('Go!')).click(); - * - * @alias by.addLocator(locatorName, functionOrScript) - * @param {string} name The name of the new locator. - * @param {Function|string} script A script to be run in the context of - * the browser. This script will be passed an array of arguments - * that contains any args passed into the locator followed by the - * element scoping the search and the css selector for the root angular - * element. It should return an array of elements. - */ - addLocator(name: string, script: string): void; - addLocator(name: string, script: Function): void; - - /** - * Find an element by binding. - * - * @view - * {{person.name}} - * - * - * @example - * var span1 = element(by.binding('person.name')); - * expect(span1.getText()).toBe('Foo'); - * - * var span2 = element(by.binding('person.email')); - * expect(span2.getText()).toBe('foo@bar.com'); - * - * @param {string} bindingDescriptor - * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} - */ - binding(bindingDescriptor: string): webdriver.Locator; - - /** - * Find an element by exact binding. - * - * @view - * {{ person.name }} - * - * {{person_phone|uppercase}} - * - * @example - * expect(element(by.exactBinding('person.name')).isPresent()).toBe(true); - * expect(element(by.exactBinding('person-email')).isPresent()).toBe(true); - * expect(element(by.exactBinding('person')).isPresent()).toBe(false); - * expect(element(by.exactBinding('person_phone')).isPresent()).toBe(true); - * expect(element(by.exactBinding('person_phone|uppercase')).isPresent()).toBe(true); - * expect(element(by.exactBinding('phone')).isPresent()).toBe(false); - * - * @param {string} bindingDescriptor - * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} - */ - exactBinding(bindingDescriptor: string): webdriver.Locator; - - /** - * Find an element by ng-model expression. - * - * @alias by.model(modelName) - * @view - * - * - * @example - * var input = element(by.model('person.name')); - * input.sendKeys('123'); - * expect(input.getAttribute('value')).toBe('Foo123'); - * - * @param {string} model ng-model expression. - */ - model(model: string): webdriver.Locator; - - /** - * Find a button by text. - * - * @view - * - * - * @example - * element(by.buttonText('Save')); - * - * @param {string} searchText - * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} - */ - buttonText(searchText: string): webdriver.Locator; - - /** - * Find a button by partial text. - * - * @view - * - * - * @example - * element(by.partialButtonText('Save')); - * - * @param {string} searchText - * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} - */ - partialButtonText(searchText: string): webdriver.Locator; - - - /** - * Find elements inside an ng-repeat. - * - * @view - *
- * {{cat.name}} - * {{cat.age}} - *
- * - *
- * {{$index}} - *
- *
- *

{{book.name}}

- *

{{book.blurb}}

- *
- * - * @example - * // Returns the DIV for the second cat. - * var secondCat = element(by.repeater('cat in pets').row(1)); - * - * // Returns the SPAN for the first cat's name. - * var firstCatName = element(by.repeater('cat in pets'). - * row(0).column('{{cat.name}}')); - * - * // Returns a promise that resolves to an array of WebElements from a column - * var ages = element.all( - * by.repeater('cat in pets').column('{{cat.age}}')); - * - * // Returns a promise that resolves to an array of WebElements containing - * // all top level elements repeated by the repeater. For 2 pets rows resolves - * // to an array of 2 elements. - * var rows = element.all(by.repeater('cat in pets')); - * - * // Returns a promise that resolves to an array of WebElements containing all - * // the elements with a binding to the book's name. - * var divs = element.all(by.repeater('book in library').column('book.name')); - * - * // Returns a promise that resolves to an array of WebElements containing - * // the DIVs for the second book. - * var bookInfo = element.all(by.repeater('book in library').row(1)); - * - * // Returns the H4 for the first book's name. - * var firstBookName = element(by.repeater('book in library'). - * row(0).column('{{book.name}}')); - * - * // Returns a promise that resolves to an array of WebElements containing - * // all top level elements repeated by the repeater. For 2 books divs - * // resolves to an array of 4 elements. - * var divs = element.all(by.repeater('book in library')); - */ - repeater(repeatDescriptor: string): RepeaterLocator; - - /** - * Find elements by CSS which contain a certain string. - * - * @view - *
    - *
  • Dog
  • - *
  • Cat
  • - *
- * - * @example - * // Returns the DIV for the dog, but not cat. - * var dog = element(by.cssContainingText('.pet', 'Dog')); - */ - cssContainingText(cssSelector: string, searchText: string): webdriver.Locator; - - /** - * Find an element by ng-options expression. - * - * @alias by.options(optionsDescriptor) - * @view - * - * - * @example - * var allOptions = element.all(by.options('c for c in colors')); - * expect(allOptions.count()).toEqual(2); - * var firstOption = allOptions.first(); - * expect(firstOption.getText()).toEqual('red'); - * - * @param {string} optionsDescriptor ng-options expression. - */ - options(optionsDescriptor: string): webdriver.Locator; - } - - var By: IProtractorLocatorStrategy; - - interface Protractor extends webdriver.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} - */ - driver: webdriver.WebDriver; - - /** - * Helper function for finding elements. - * - * @type {function(webdriver.Locator): ElementFinder} - */ - element(locator: webdriver.Locator): ElementFinder; - - /** - * Shorthand function for finding elements by css. - * - * @type {function(string): ElementFinder} - */ - $(selector: string): ElementFinder; - - /** - * Shorthand function for finding arrays of elements by css. - * - * @type {function(string): ElementArrayFinder} - */ - $$(selector: string): ElementArrayFinder; - - /** - * All get methods will be resolved against this base URL. Relative URLs are = - * resolved the way anchor tags resolve. - * - * @type {string} - */ - baseUrl: 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} - */ - rootEl: string; - - /** - * 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} - */ - ignoreSynchronization: boolean; - - /** - * Timeout in milliseconds to wait for pages to load when calling `get`. - * - * @type {number} - */ - getPageTimeout: number; - - /** - * An object that holds custom test parameters. - * - * @type {Object} - */ - params: any; - - /** - * The reset URL to use between page loads. - * - * @type {string} - */ - resetUrl: string; - - /** - * Instruct webdriver to wait until Angular has finished rendering and has - * no outstanding $http calls before continuing. - * - * @return {!webdriver.promise.Promise} A promise that will resolve to the - * scripts return value. - */ - waitForAngular(): webdriver.promise.Promise; - - /** - * 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. - * - * @example - * browser.addMockModule('modName', function() { - * angular.module('modName', []).value('foo', 'bar'); - * }); - * - * @param {!string} name The name of the module to load or override. - * @param {!string|Function} script The JavaScript to load the module. - * @param {...*} varArgs Any additional arguments will be provided to - * the script and may be referenced using the `arguments` object. - */ - addMockModule(name: string, script: string, ...varArgs: any[]): void; - addMockModule(name: string, script: Function, ...varArgs: any[]): void; - - /** - * Clear the list of registered mock modules. - */ - clearMockModules(): void; - - /** - * Remove a registered mock module. - * - * @example - * browser.removeMockModule('modName'); - * - * @param {!string} name The name of the module to remove. - */ - removeMockModule(name: string): void; - - /** - * @see webdriver.WebDriver.get - * - * Navigate to the given destination and loads mock modules before - * Angular. Assumes that the page being loaded uses Angular. - * If you need to access a page which does not have Angular on load, use - * the wrapped webdriver directly. - * - * @param {string} destination Destination URL. - * @param {number=} opt_timeout Number of milliseconds to wait for Angular to - * start. - */ - get(destination: string, opt_timeout?: number): webdriver.promise.Promise; - - /** - * See webdriver.WebDriver.refresh - * - * Makes a full reload of the current page and loads mock modules before - * Angular. Assumes that the page being loaded uses Angular. - * If you need to access a page which does not have Angular on load, use - * the wrapped webdriver directly. - * - * @param {number=} opt_timeout Number of seconds to wait for Angular to start. - */ - refresh(opt_timeout?: number): webdriver.promise.Promise; - - /** - * Browse to another page using in-page navigation. - * - * @param {string} url In page URL using the same syntax as $location.url() - * @returns {!webdriver.promise.Promise} A promise that will resolve once - * page has been changed. - */ - setLocation(url: string): webdriver.promise.Promise; - - /** - * Returns the current absolute url from AngularJS. - */ - getLocationAbsUrl(): webdriver.promise.Promise; - - /** - * 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 - * - * @example - * 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. - */ - debugger(): void; - - /** - * Beta (unstable) pause function for debugging webdriver tests. Use - * browser.pause() in your test to enter the protractor debugger from that - * point in the control flow. - * Does not require changes to the command line (no need to add 'debug'). - * - * @example - * element(by.id('foo')).click(); - * browser.pause(); - * // Execution will stop before the next click action. - * element(by.id('bar')).click(); - * - * @param {number=} opt_debugPort Optional port to use for the debugging process - */ - pause(opt_debugPort?: number): void; - } - - // Interface for the global browser object. - interface IBrowser extends Protractor { - /** - * Fork another instance of protractor for use in interactive tests. - * - * @param {boolean} opt_useSameUrl Whether to navigate to current url on creation - * @param {boolean} opt_copyMockModules Whether to apply same mock modules on creation - * @return {Protractor} a protractor instance. - */ - forkNewDriverInstance(opt_useSameUrl?: boolean, opt_copyMockModules?: boolean): Protractor; - - /** - * Get the processed configuration object that is currently being run. This will contain - * the specs and capabilities properties of the current runner instance. - * - * Set by the runner. - * - * @return {webdriver.promise.Promise} A promise which resolves to the capabilities object. - */ - getProcessedConfig(): webdriver.promise.Promise; - } - - /** - * Create a new instance of Protractor by wrapping a webdriver instance. - * - * @param {webdriver.WebDriver} webdriver The configured webdriver instance. - * @param {string=} opt_baseUrl A URL to prepend to relative gets. - * @return {Protractor} - */ - function wrapDriver(webdriver: webdriver.WebDriver, opt_baseUrl?: string, opt_rootElement?: string): Protractor; -} - -interface cssSelectorHelper { - (cssLocator: string): protractor.ElementFinder; -} - -interface cssArraySelectorHelper { - (cssLocator: string): protractor.ElementArrayFinder; -} - -declare var browser: protractor.IBrowser; -declare var by: protractor.IProtractorLocatorStrategy; -declare var By: protractor.IProtractorLocatorStrategy; -declare var element: protractor.Element; -declare var $: cssSelectorHelper; -declare var $$: cssArraySelectorHelper; - -declare module 'protractor' { - export = protractor; -} diff --git a/protractor/tsconfig.json b/protractor/tsconfig.json deleted file mode 100644 index c16efc5afc..0000000000 --- a/protractor/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "angular-protractor-tests.ts" - ] -} \ No newline at end of file diff --git a/selenium-webdriver/index.d.ts b/selenium-webdriver/index.d.ts index 548048b695..702ff68c33 100644 --- a/selenium-webdriver/index.d.ts +++ b/selenium-webdriver/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Selenium WebDriverJS 2.44.0 -// Project: https://code.google.com/p/selenium/ -// Definitions by: Bill Armstrong , Yuki Kokubun +// Type definitions for Selenium WebDriverJS 2.53.1 +// Project: https://github.com/SeleniumHQ/selenium/tree/master/javascript/node/selenium-webdriver +// Definitions by: Bill Armstrong , Yuki Kokubun , Craig Nishina // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace chrome { @@ -19,8 +19,7 @@ declare namespace chrome { * {@code null} to use the currently active flow. * @constructor */ - constructor(opt_config?: webdriver.Capabilities, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); - constructor(opt_config?: Options, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: Options|webdriver.Capabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); } interface IOptionsValues { @@ -240,6 +239,53 @@ declare namespace chrome { setChromeLogFile(path: string): Options; + /** + * Sets the directory to store Chrome minidumps in. This option is only + * supported when ChromeDriver is running on Linux. + * @param {string} path The directory path. + * @return {!Options} A self reference. + */ + setChromeMinidumpPath(path: string): Options; + + + /** + * Configures Chrome to emulate a mobile device. For more information, refer + * to the ChromeDriver project page on [mobile emulation][em]. Configuration + * options include: + * + * - `deviceName`: The name of a pre-configured [emulated device][devem] + * - `width`: screen width, in pixels + * - `height`: screen height, in pixels + * - `pixelRatio`: screen pixel ratio + * + * __Example 1: Using a Pre-configured Device__ + * + * let options = new chrome.Options().setMobileEmulation( + * {deviceName: 'Google Nexus 5'}); + * + * let driver = new chrome.Driver(options); + * + * __Example 2: Using Custom Screen Configuration__ + * + * let options = new chrome.Options().setMobileEmulation({ + * width: 360, + * height: 640, + * pixelRatio: 3.0 + * }); + * + * let driver = new chrome.Driver(options); + * + * + * [em]: https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation + * [devem]: https://developer.chrome.com/devtools/docs/device-mode + * + * @param {?({deviceName: string}| + * {width: number, height: number, pixelRatio: number})} config The + * mobile emulation configuration, or `null` to disable emulation. + * @return {!Options} A self reference. + */ + setMobileEmulation(config: any): Options; + /** * Sets the proxy settings for the new session. * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. @@ -255,21 +301,6 @@ declare namespace chrome { * @return {!webdriver.Capabilities} The capabilities. */ toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; - - - /** - * Converts this instance to its JSON wire protocol representation. Note this - * function is an implementation not intended for general use. - * @return {{args: !Array., - * binary: (string|undefined), - * detach: boolean, - * extensions: !Array., - * localState: (Object|undefined), - * logFile: (string|undefined), - * prefs: (Object|undefined)}} The JSON wire protocol representation - * of this instance. - */ - toJSON(): IOptionsValues; } /** @@ -348,8 +379,7 @@ declare namespace chrome { * configuration to use. * @return {!ServiceBuilder} A self reference. */ - setStdio(config: string): ServiceBuilder; - setStdio(config: any[]): ServiceBuilder; + setStdio(config: string|Array): ServiceBuilder; /** @@ -368,7 +398,7 @@ declare namespace chrome { * @throws {Error} If the driver exectuable was not specified and a default * could not be found on the current PATH. */ - build(): any; + build(): remote.DriverService; } /** @@ -377,395 +407,1325 @@ declare namespace chrome { * a ChromeDriver executable found on the system PATH. * @return {!remote.DriverService} The default ChromeDriver service. */ - function getDefaultService(): any; + function getDefaultService(): remote.DriverService; /** * Sets the default service to use for new ChromeDriver instances. * @param {!remote.DriverService} service The service to use. * @throws {Error} If the default service is currently running. */ - function setDefaultService(service: any): void; + function setDefaultService(service: remote.DriverService): void; } -declare namespace firefox { - /** - * Manages a Firefox subprocess configured for use with WebDriver. - */ - class Binary { - /** - * @param {string=} opt_exe Path to the Firefox binary to use. If not - * specified, will attempt to locate Firefox on the current system. - * @constructor - */ - constructor(opt_exe?: string); +declare namespace edge { - /** - * Add arguments to the command line used to start Firefox. - * @param {...(string|!Array.)} var_args Either the arguments to add as - * varargs, or the arguments as an array. - */ - addArguments(...var_args: string[]): void; - - - /** - * Launches Firefox and eturns a promise that will be fulfilled when the process - * terminates. - * @param {string} profile Path to the profile directory to use. - * @return {!promise.Promise.} A promise for the process result. - * @throws {Error} If this instance has already been started. - */ - launch(profile: string): webdriver.promise.Promise; - - - /** - * Kills the managed Firefox process. - * @return {!promise.Promise} A promise for when the process has terminated. - */ - kill(): webdriver.promise.Promise; - } - - /** - * A WebDriver client for Firefox. - * - * @extends {webdriver.WebDriver} - */ class Driver extends webdriver.WebDriver { - /** - * @param {(Options|webdriver.Capabilities|Object)=} opt_config The - * configuration options for this driver, specified as either an - * {@link Options} or {@link webdriver.Capabilities}, or as a raw hash - * object. - * @param {webdriver.promise.ControlFlow=} opt_flow The flow to - * schedule commands through. Defaults to the active flow object. - * @constructor - */ - constructor(opt_config?: webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); - constructor(opt_config?: any, opt_flow?: webdriver.promise.ControlFlow); + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@linkplain #getDefaultService default service} by default. + * @param {promise.ControlFlow=} opt_flow The control flow to use, or + * {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities|Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; } /** - * Configuration options for the FirefoxDriver. + * Class for managing MicrosoftEdgeDriver specific options. */ class Options { - /** - * @constructor - */ - constructor(); - /** - * Sets the profile to use. The profile may be specified as a - * {@link Profile} object or as the path to an existing Firefox profile to use - * as a template. - * - * @param {(string|!Profile)} profile The profile to use. - * @return {!Options} A self reference. - */ - setProfile(profile: string): Options; - setProfile(profile: Profile): Options; + /** + * Extracts the MicrosoftEdgeDriver specific options from the given + * capabilities object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The MicrosoftEdgeDriver options. + */ + static fromCapabilities(cap: webdriver.Capabilities): Options; + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; - /** - * Sets the binary to use. The binary may be specified as the path to a Firefox - * executable, or as a {@link Binary} object. - * - * @param {(string|!Binary)} binary The binary to use. - * @return {!Options} A self reference. - */ - setBinary(binary: string): Options; - setBinary(binary: Binary): Options; + /** + * Sets the page load strategy for Edge. + * Supported values are "normal", "eager", and "none"; + * + * @param {string} pageLoadStrategy The page load strategy to use. + * @return {!Options} A self reference. + */ + setPageLoadStrategy(pageLoadStrategy: string): Options; - - /** - * Sets the logging preferences for the new session. - * @param {webdriver.logging.Preferences} prefs The logging preferences. - * @return {!Options} A self reference. - */ - setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; - - - /** - * Sets the proxy to use. - * - * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - - - /** - * Converts these options to a {@link webdriver.Capabilities} instance. - * - * @return {!webdriver.Capabilities} A new capabilities object. - */ - toCapabilities(opt_remote?: any): webdriver.Capabilities; + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; } /** - * Models a Firefox proifle directory for use with the FirefoxDriver. The - * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} - * is called. + * Creates {@link remote.DriverService} instances that manage a + * MicrosoftEdgeDriver server in a child process. */ - class Profile { - /** - * @param {string=} opt_dir Path to an existing Firefox profile directory to - * use a template for this profile. If not specified, a blank profile will - * be used. - * @constructor - */ - constructor(opt_dir?: string); + class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the MicrosoftEdgeDriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the + * MicrosoftEdgeDriver cannot be found on the PATH. + */ + constructor(opt_exe?: string); - /** - * Registers an extension to be included with this profile. - * @param {string} extension Path to the extension to include, as either an - * unpacked extension directory or the path to a xpi file. - */ - addExtension(extension: string): void; + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array.)} + * config The configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string|Array): ServiceBuilder; + /** + * Sets the port to start the MicrosoftEdgeDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; - /** - * Sets a desired preference for this profile. - * @param {string} key The preference key. - * @param {(string|number|boolean)} value The preference value. - * @throws {Error} If attempting to set a frozen preference. - */ - setPreference(key: string, value: string): void; - setPreference(key: string, value: number): void; - setPreference(key: string, value: boolean): void; + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: Object): ServiceBuilder; - - /** - * Returns the currently configured value of a profile preference. This does - * not include any defaults defined in the profile's template directory user.js - * file (if a template were specified on construction). - * @param {string} key The desired preference. - * @return {(string|number|boolean|undefined)} The current value of the - * requested preference. - */ - getPreference(key: string): any; - - - /** - * @return {number} The port this profile is currently configured to use, or - * 0 if the port will be selected at random when the profile is written - * to disk. - */ - getPort(): number; - - - /** - * Sets the port to use for the WebDriver extension loaded by this profile. - * @param {number} port The desired port, or 0 to use any free port. - */ - setPort(port: number): void; - - - /** - * @return {boolean} Whether the FirefoxDriver is configured to automatically - * accept untrusted SSL certificates. - */ - acceptUntrustedCerts(): boolean; - - - /** - * Sets whether the FirefoxDriver should automatically accept untrusted SSL - * certificates. - * @param {boolean} value . - */ - setAcceptUntrustedCerts(value: boolean): void; - - - /** - * Sets whether to assume untrusted certificates come from untrusted issuers. - * @param {boolean} value . - */ - setAssumeUntrustedCertIssuer(value: boolean): void; - - - /** - * @return {boolean} Whether to assume untrusted certs come from untrusted - * issuers. - */ - assumeUntrustedCertIssuer(): boolean; - - - /** - * Sets whether to use native events with this profile. - * @param {boolean} enabled . - */ - setNativeEventsEnabled(enabled: boolean): void; - - - /** - * Returns whether native events are enabled in this profile. - * @return {boolean} . - */ - nativeEventsEnabled(): boolean; - - - /** - * Writes this profile to disk. - * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver - * extension from the generated profile. Used to reduce the size of an - * {@link #encode() encoded profile} since the server will always install - * the extension itself. - * @return {!promise.Promise.} A promise for the path to the new - * profile directory. - */ - writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; - - - /** - * Encodes this profile as a zipped, base64 encoded directory. - * @return {!promise.Promise.} A promise for the encoded profile. - */ - encode(): webdriver.promise.Promise; + /** + * Creates a new DriverService using this instance's current configuration. + * @return {!remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; } + + /** + * Returns the default MicrosoftEdgeDriver service. If such a service has + * not been configured, one will be constructed using the default configuration + * for an MicrosoftEdgeDriver executable found on the system PATH. + * @return {!remote.DriverService} The default MicrosoftEdgeDriver service. + */ + function getDefaultService(): remote.DriverService; + + /** + * Sets the default service to use for new MicrosoftEdgeDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ + function setDefaultService(service: remote.DriverService): void; } declare namespace executors { /** * Creates a command executor that uses WebDriver's JSON wire protocol. - * @param url The server's URL, or a promise that will resolve to that URL. - * @returns {!webdriver.CommandExecutor} The new command executor. + * @param {(string|!promise.Promise)} url The server's URL, + * or a promise that will resolve to that URL. + * @param {?string=} opt_proxy (optional) The URL of the HTTP proxy for the + * client to use. + * @returns {!./lib/command.Executor} The new command executor. */ - function createExecutor(url: string): webdriver.CommandExecutor; - function createExecutor(url: webdriver.promise.Promise): webdriver.CommandExecutor; + function createExecutor(url: string|webdriver.promise.Promise, opt_agent?: string, opt_proxy?: string): webdriver.Executor; +} + +declare namespace firefox { + /** + * Manages a Firefox subprocess configured for use with WebDriver. + */ + class Binary { + /** + * @param {string=} opt_exe Path to the Firefox binary to use. If not + * specified, will attempt to locate Firefox on the current system. + * @constructor + */ + constructor(opt_exe?: string); + + /** + * Add arguments to the command line used to start Firefox. + * @param {...(string|!Array.)} var_args Either the arguments to add as + * varargs, or the arguments as an array. + */ + addArguments(...var_args: string[]): void; + + + /** + * Launches Firefox and eturns a promise that will be fulfilled when the process + * terminates. + * @param {string} profile Path to the profile directory to use. + * @return {!promise.Promise.} A promise for the process result. + * @throws {Error} If this instance has already been started. + */ + launch(profile: string): webdriver.promise.Promise; + + + /** + * Kills the managed Firefox process. + * @return {!promise.Promise} A promise for when the process has terminated. + */ + kill(): webdriver.promise.Promise; + } + + /** + * Models a Firefox proifle directory for use with the FirefoxDriver. The + * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} + * is called. + */ + class Profile { + /** + * @param {string=} opt_dir Path to an existing Firefox profile directory to + * use a template for this profile. If not specified, a blank profile will + * be used. + * @constructor + */ + constructor(opt_dir?: string); + + /** + * Registers an extension to be included with this profile. + * @param {string} extension Path to the extension to include, as either an + * unpacked extension directory or the path to a xpi file. + */ + addExtension(extension: string): void; + + + /** + * Sets a desired preference for this profile. + * @param {string} key The preference key. + * @param {(string|number|boolean)} value The preference value. + * @throws {Error} If attempting to set a frozen preference. + */ + setPreference(key: string, value: string): void; + setPreference(key: string, value: number): void; + setPreference(key: string, value: boolean): void; + + + /** + * Returns the currently configured value of a profile preference. This does + * not include any defaults defined in the profile's template directory user.js + * file (if a template were specified on construction). + * @param {string} key The desired preference. + * @return {(string|number|boolean|undefined)} The current value of the + * requested preference. + */ + getPreference(key: string): any; + + + /** + * @return {number} The port this profile is currently configured to use, or + * 0 if the port will be selected at random when the profile is written + * to disk. + */ + getPort(): number; + + + /** + * Sets the port to use for the WebDriver extension loaded by this profile. + * @param {number} port The desired port, or 0 to use any free port. + */ + setPort(port: number): void; + + + /** + * @return {boolean} Whether the FirefoxDriver is configured to automatically + * accept untrusted SSL certificates. + */ + acceptUntrustedCerts(): boolean; + + + /** + * Sets whether the FirefoxDriver should automatically accept untrusted SSL + * certificates. + * @param {boolean} value . + */ + setAcceptUntrustedCerts(value: boolean): void; + + + /** + * Sets whether to assume untrusted certificates come from untrusted issuers. + * @param {boolean} value . + */ + setAssumeUntrustedCertIssuer(value: boolean): void; + + + /** + * @return {boolean} Whether to assume untrusted certs come from untrusted + * issuers. + */ + assumeUntrustedCertIssuer(): boolean; + + + /** + * Sets whether to use native events with this profile. + * @param {boolean} enabled . + */ + setNativeEventsEnabled(enabled: boolean): void; + + + /** + * Returns whether native events are enabled in this profile. + * @return {boolean} . + */ + nativeEventsEnabled(): boolean; + + + /** + * Writes this profile to disk. + * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver + * extension from the generated profile. Used to reduce the size of an + * {@link #encode() encoded profile} since the server will always install + * the extension itself. + * @return {!promise.Promise.} A promise for the path to the new + * profile directory. + */ + writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; + + + /** + * Encodes this profile as a zipped, base64 encoded directory. + * @return {!promise.Promise.} A promise for the encoded profile. + */ + encode(): webdriver.promise.Promise; + } + + /** + * Configuration options for the FirefoxDriver. + */ + class Options { + /** + * Sets the profile to use. The profile may be specified as a + * {@link Profile} object or as the path to an existing Firefox profile to use + * as a template. + * + * @param {(string|!Profile)} profile The profile to use. + * @return {!Options} A self reference. + */ + setProfile(profile: string|any): Options; + + /** + * Sets the binary to use. The binary may be specified as the path to a Firefox + * executable, or as a {@link Binary} object. + * + * @param {(string|!Binary)} binary The binary to use. + * @return {!Options} A self reference. + */ + setBinary(binary: string|any): Options; + + /** + * Sets the logging preferences for the new session. + * @param {logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the proxy to use. + * + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Sets whether to use Mozilla's Marionette to drive the browser. + * + * @see https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver + */ + useMarionette(marionette: any): Options; + + /** + * Converts these options to a {@link capabilities.Capabilities} instance. + * + * @return {!capabilities.Capabilities} A new capabilities object. + */ + toCapabilities(): webdriver.Capabilities; + } + + /** + * @return {string} . + * @throws {Error} + */ + function findWires(): string; + + /** + * @param {(string|!Binary)} binary . + * @return {!remote.DriverService} . + */ + function createWiresService(binary: string|any): remote.DriverService; + + /** + * @param {(Profile|string)} profile The profile to prepare. + * @param {number} port The port the FirefoxDriver should listen on. + * @return {!Promise} a promise for the path to the profile directory. + */ + function prepareProfile(profile: string|any, port: number): any; + + /** + * A WebDriver client for Firefox. + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(Options|capabilities.Capabilities|Object)=} opt_config The + * configuration options for this driver, specified as either an + * {@link Options} or {@link capabilities.Capabilities}, or as a raw hash + * object. + * @param {promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + */ + constructor(opt_config?: Options|webdriver.Capabilities|Object, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; + } +} + +declare namespace http { + /** + * Converts a headers map to a HTTP header block string. + * @param {!Map} headers The map to convert. + * @return {string} The headers as a string. + */ + function headersToString(headers: any): string; + + /** + * Represents a HTTP request message. This class is a "partial" request and only + * defines the path on the server to send a request to. It is each client's + * responsibility to build the full URL for the final request. + * @final + */ + class HttpRequest { + /** + * @param {string} method The HTTP method to use for the request. + * @param {string} path The path on the server to send the request to. + * @param {Object=} opt_data This request's non-serialized JSON payload data. + */ + constructor(method: string, path: string, opt_data?: Object); + + /** @override */ + toString(): string; + } + + /** + * Represents a HTTP response message. + * @final + */ + class HttpResponse { + /** + * @param {number} status The response code. + * @param {!Object} headers The response headers. All header names + * will be converted to lowercase strings for consistent lookups. + * @param {string} body The response body. + */ + constructor(status: number, headers: Object, body: string); + + /** @override */ + toString(): string; + } + + + function post(path: string): any; + function del(path: string): any; + function get(path: string): any; + function resource(method: string, path: string): any; + + /** + * A basic HTTP client used to send messages to a remote end. + */ + class HttpClient { + /** + * @param {string} serverUrl URL for the WebDriver server to send commands to. + * @param {http.Agent=} opt_agent The agent to use for each request. + * Defaults to `http.globalAgent`. + * @param {?string=} opt_proxy The proxy to use for the connection to the + * server. Default is to use no proxy. + */ + constructor(serverUrl: string, opt_agent?: any, opt_proxy?: string); + + /** + * Sends a request to the server. The client will automatically follow any + * redirects returned by the server, fulfilling the returned promise with the + * final response. + * + * @param {!HttpRequest} httpRequest The request to send. + * @return {!promise.Promise} A promise that will be fulfilled + * with the server's response. + */ + send(httpRequest: HttpRequest): webdriver.promise.Promise; + } + + /** + * Sends a single HTTP request. + * @param {!Object} options The request options. + * @param {function(!HttpResponse)} onOk The function to call if the + * request succeeds. + * @param {function(!Error)} onError The function to call if the request fails. + * @param {?string=} opt_data The data to send with the request. + * @param {?string=} opt_proxy The proxy server to use for the request. + */ + function sendRequest(options: Object, onOk: any, onError: any, opt_data?: string, opt_proxy?: string): any; + + /** + * A command executor that communicates with the server using HTTP + JSON. + * + * By default, each instance of this class will use the legacy wire protocol + * from [Selenium project][json]. The executor will automatically switch to the + * [W3C wire protocol][w3c] if the remote end returns a compliant response to + * a new session command. + * + * [json]: https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol + * [w3c]: https://w3c.github.io/webdriver/webdriver-spec.html + * + * @implements {cmd.Executor} + */ + class Executor { + /** + * @param {!HttpClient} client The client to use for sending requests to the + * server. + */ + constructor(client: HttpClient); + + /** + * Defines a new command for use with this executor. When a command is sent, + * the {@code path} will be preprocessed using the command's parameters; any + * path segments prefixed with ":" will be replaced by the parameter of the + * same name. For example, given "/person/:name" and the parameters + * "{name: 'Bob'}", the final command path will be "/person/Bob". + * + * @param {string} name The command name. + * @param {string} method The HTTP method to use when sending this command. + * @param {string} path The path to send the command to, relative to + * the WebDriver server's command root and of the form + * "/path/:variable/segment". + */ + defineCommand(name: string, method: string, path: string): void; + + /** @override */ + execute(command: any): any; + } + + /** + * @param {string} str . + * @return {?} . + */ + function tryParse(str: string): any; + + /** + * Callback used to parse {@link HttpResponse} objects from a + * {@link HttpClient}. + * @param {!HttpResponse} httpResponse The HTTP response to parse. + * @param {boolean} w3c Whether the response should be processed using the + * W3C wire protocol. + * @return {{value: ?}} The parsed response. + * @throws {WebDriverError} If the HTTP response is an error. + */ + function parseHttpResponse(httpResponse: HttpResponse, w3c: boolean): any; + + /** + * Builds a fully qualified path using the given set of command parameters. Each + * path segment prefixed with ':' will be replaced by the value of the + * corresponding parameter. All parameters spliced into the path will be + * removed from the parameter map. + * @param {string} path The original resource path. + * @param {!Object<*>} parameters The parameters object to splice into the path. + * @return {string} The modified path. + */ + function buildPath(path: string, parameters: Object): string; +} + +declare namespace ie { + + /** + * A WebDriver client for Microsoft's Internet Explorer. + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {promise.ControlFlow=} opt_flow The control flow to use, + * or {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities|Options, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; + } + + /** + * Class for managing IEDriver specific options. + */ + class Options { + constructor(); + + /** + * Extracts the IEDriver specific options from the given capabilities + * object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The IEDriver options. + */ + static fromCapabilities(caps: webdriver.Capabilities): Options; + + /** + * Whether to disable the protected mode settings check when the session is + * created. Disbling this setting may lead to significant instability as the + * browser may become unresponsive/hang. Only "best effort" support is provided + * when using this capability. + * + * For more information, refer to the IEDriver's + * [required system configuration](http://goo.gl/eH0Yi3). + * + * @param {boolean} ignoreSettings Whether to ignore protected mode settings. + * @return {!Options} A self reference. + */ + introduceFlakinessByIgnoringProtectedModeSettings(ignoreSettings: boolean): Options; + + /** + * Indicates whether to skip the check that the browser's zoom level is set to + * 100%. + * + * @param {boolean} ignore Whether to ignore the browser's zoom level settings. + * @return {!Options} A self reference. + */ + ignoreZoomSetting(ignore: boolean): Options; + + /** + * Sets the initial URL loaded when IE starts. This is intended to be used with + * {@link #ignoreProtectedModeSettings} to allow the user to initialize IE in + * the proper Protected Mode zone. Setting this option may cause browser + * instability or flaky and unresponsive code. Only "best effort" support is + * provided when using this option. + * + * @param {string} url The initial browser URL. + * @return {!Options} A self reference. + */ + initialBrowserUrl(url: string): Options; + + /** + * Configures whether to enable persistent mouse hovering (true by default). + * Persistent hovering is achieved by continuously firing mouse over events at + * the last location the mouse cursor has been moved to. + * + * @param {boolean} enable Whether to enable persistent hovering. + * @return {!Options} A self reference. + */ + enablePersistentHover(enable: boolean): Options; + + /** + * Configures whether the driver should attempt to remove obsolete + * {@linkplain webdriver.WebElement WebElements} from its internal cache on + * page navigation (true by default). Disabling this option will cause the + * driver to run with a larger memory footprint. + * + * @param {boolean} enable Whether to enable element reference cleanup. + * @return {!Options} A self reference. + */ + enableElementCacheCleanup(enable: boolean): Options; + + /** + * Configures whether to require the IE window to have input focus before + * performing any user interactions (i.e. mouse or keyboard events). This + * option is disabled by default, but delivers much more accurate interaction + * events when enabled. + * + * @param {boolean} require Whether to require window focus. + * @return {!Options} A self reference. + */ + requireWindowFocus(require: boolean): Options; + + /** + * Configures the timeout, in milliseconds, that the driver will attempt to + * located and attach to a newly opened instance of Internet Explorer. The + * default is zero, which indicates waiting indefinitely. + * + * @param {number} timeout How long to wait for IE. + * @return {!Options} A self reference. + */ + browserAttachTimeout(timeout: number): Options; + + /** + * Configures whether to launch Internet Explorer using the CreateProcess API. + * If this option is not specified, IE is launched using IELaunchURL, if + * available. For IE 8 and above, this option requires the TabProcGrowth + * registry value to be set to 0. + * + * @param {boolean} force Whether to use the CreateProcess API. + * @return {!Options} A self reference. + */ + forceCreateProcessApi(force: boolean): Options; + + /** + * Specifies command-line switches to use when launching Internet Explorer. + * This is only valid when used with {@link #forceCreateProcessApi}. + * + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: Array): Options; + + /** + * Configures whether proxies should be configured on a per-process basis. If + * not set, setting a {@linkplain #setProxy proxy} will configure the system + * proxy. The default behavior is to use the system proxy. + * + * @param {boolean} enable Whether to enable per-process proxy settings. + * @return {!Options} A self reference. + */ + usePerProcessProxy(enable: boolean): Options; + + /** + * Configures whether to clear the cache, cookies, history, and saved form data + * before starting the browser. _Using this capability will clear session data + * for all running instances of Internet Explorer, including those started + * manually._ + * + * @param {boolean} cleanSession Whether to clear all session data on startup. + * @return {!Options} A self reference. + */ + ensureCleanSession(cleanSession: boolean): Options; + + /** + * Sets the path to the log file the driver should log to. + * @param {string} file The log file path. + * @return {!Options} A self reference. + */ + setLogFile(file: string): Options; + + /** + * Sets the IEDriverServer's logging {@linkplain Level level}. + * @param {Level} level The logging level. + * @return {!Options} A self reference. + */ + setLogLevel(level: webdriver.logging.Level): Options; + + /** + * Sets the IP address of the driver's host adapter. + * @param {string} host The IP address to use. + * @return {!Options} A self reference. + */ + setHost(host: string): Options; + + /** + * Sets the path of the temporary data directory to use. + * @param {string} path The log file path. + * @return {!Options} A self reference. + */ + setExtractPath(path: string): Options; + + /** + * Sets whether the driver should start in silent mode. + * @param {boolean} silent Whether to run in silent mode. + * @return {!Options} A self reference. + */ + silent(silent: boolean): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + } + +} + +declare namespace opera { + /** + * Creates {@link remote.DriverService} instances that manages an + * [OperaDriver](https://github.com/operasoftware/operachromiumdriver) + * server in a child process. + */ + class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the operadriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the operadriver + * cannot be found on the PATH. + */ + constructor(opt_exe?: string); + + /** + * Sets the port to start the OperaDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + /** + * Sets the path of the log file the driver should log to. If a log file is + * not specified, the driver will log to stderr. + * @param {string} path Path of the log file to use. + * @return {!ServiceBuilder} A self reference. + */ + loggingTo(path: string): ServiceBuilder; + + /** + * Enables verbose logging. + * @return {!ServiceBuilder} A self reference. + */ + enableVerboseLogging(): ServiceBuilder; + + /** + * Silence sthe drivers output. + * @return {!ServiceBuilder} A self reference. + */ + silent(): ServiceBuilder; + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array)} + * config The configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string|Array): ServiceBuilder; + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: Object): ServiceBuilder; + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {!remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; + } + + /** + * Sets the default service to use for new OperaDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ + function setDefaultService(service: remote.DriverService): any; + + /** + * Returns the default OperaDriver service. If such a service has not been + * configured, one will be constructed using the default configuration for + * a OperaDriver executable found on the system PATH. + * @return {!remote.DriverService} The default OperaDriver service. + */ + function getDefaultService(): remote.DriverService; + + /** + * Class for managing {@linkplain Driver OperaDriver} specific options. + */ + class Options { + /** + * Extracts the OperaDriver specific options from the given capabilities + * object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The OperaDriver options. + */ + static fromCapabilities(caps: webdriver.Capabilities): Options; + + /** + * Add additional command line arguments to use when launching the Opera + * browser. Each argument may be specified with or without the "--" prefix + * (e.g. "--foo" and "foo"). Arguments with an associated value should be + * delimited by an "=": "foo=bar". + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: Array): Options; + + /** + * Add additional extensions to install when launching Opera. Each extension + * should be specified as the path to the packed CRX file, or a Buffer for an + * extension. + * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The + * extensions to add. + * @return {!Options} A self reference. + */ + addExtensions(...var_args: Array): Options; + + /** + * Sets the path to the Opera binary to use. On Mac OS X, this path should + * reference the actual Opera executable, not just the application binary. The + * binary path be absolute or relative to the operadriver server executable, but + * it must exist on the machine that will launch Opera. + * + * @param {string} path The path to the Opera binary to use. + * @return {!Options} A self reference. + */ + setOperaBinaryPath(path: string): Options; + + /** + * Sets the logging preferences for the new session. + * @param {!./lib/logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; + } + + class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@link getDefaultService default service} by default. + * @param {promise.ControlFlow=} opt_flow The control flow to use, + * or {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities|Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; + } +} + +declare namespace remote { + /** + * A record object that defines the configuration options for a DriverService + * instance. + * + * @record + */ + interface ServiceOptions {} + + /** + * Manages the life and death of a native executable WebDriver server. + * + * It is expected that the driver server implements the + * https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol. + * Furthermore, the managed server should support multiple concurrent sessions, + * so that this class may be reused for multiple clients. + */ + class DriverService { + /** + * @param {string} executable Path to the executable to run. + * @param {!ServiceOptions} options Configuration options for the service. + */ + constructor(executable: string, options: ServiceOptions); + + /** + * @return {!promise.Promise} A promise that resolves to + * the server's address. + * @throws {Error} If the server has not been started. + */ + address(): webdriver.promise.Promise; + + /** + * Returns whether the underlying process is still running. This does not take + * into account whether the process is in the process of shutting down. + * @return {boolean} Whether the underlying service process is running. + */ + isRunning(): boolean; + + /** + * Starts the server if it is not already running. + * @param {number=} opt_timeoutMs How long to wait, in milliseconds, for the + * server to start accepting requests. Defaults to 30 seconds. + * @return {!promise.Promise} A promise that will resolve + * to the server's base URL when it has started accepting requests. If the + * timeout expires before the server has started, the promise will be + * rejected. + */ + start(opt_timeoutMs?: number): webdriver.promise.Promise; + + /** + * Stops the service if it is not currently running. This function will kill + * the server immediately. To synchronize with the active control flow, use + * {@link #stop()}. + * @return {!promise.Promise} A promise that will be resolved when + * the server has been stopped. + */ + kill(): webdriver.promise.Promise; + + /** + * Schedules a task in the current control flow to stop the server if it is + * currently running. + * @return {!promise.Promise} A promise that will be resolved when + * the server has been stopped. + */ + stop(): webdriver.promise.Promise; + } +} + +declare namespace safari { + class Server {} + + /** + * @return {!Promise} A promise that will resolve with the path + * to Safari on the current system. + */ + function findSafariExecutable(): any; + + /** + * @param {string} serverUrl The URL to connect to. + * @return {!Promise} A promise for the path to a file that Safari can + * open on start-up to trigger a new connection to the WebSocket server. + */ + function createConnectFile(serverUrl: string): any; + + /** + * Deletes all session data files if so desired. + * @param {!Object} desiredCapabilities . + * @return {!Array} A list of promises for the deleted files. + */ + function cleanSession(desiredCapabilities: webdriver.Capabilities): any[]; + + /** @return {string} . */ + function getRandomString(): string; + + /** + * @implements {command.Executor} + */ + class CommandExecutor { + } + + /** + * Configuration options specific to the {@link Driver SafariDriver}. + */ + class Options { + /** + * Extracts the SafariDriver specific options from the given capabilities + * object. + * @param {!Capabilities} capabilities The capabilities object. + * @return {!Options} The ChromeDriver options. + */ + static fromCapabilities(capabilities: webdriver.Capabilities): Options; + + /** + * Sets whether to force Safari to start with a clean session. Enabling this + * option will cause all global browser data to be deleted. + * @param {boolean} clean Whether to make sure the session has no cookies, + * cache entries, local storage, or databases. + * @return {!Options} A self reference. + */ + setCleanSession(clean: boolean): Options; + + /** + * Sets the logging preferences for the new session. + * @param {!./lib/logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Converts this options instance to a {@link Capabilities} object. + * @param {Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + } + + /** + * A WebDriver client for Safari. This class should never be instantiated + * directly; instead, use the {@linkplain ./builder.Builder Builder}: + * + * var driver = new Builder() + * .forBrowser('safari') + * .build(); + * + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(Options|Capabilities)=} opt_config The configuration + * options for the new session. + * @param {promise.ControlFlow=} opt_flow The control flow to create + * the driver under. + */ + constructor(opt_config?: Options|webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); + + } } declare namespace webdriver { namespace error { - interface IErrorCode { - SUCCESS: number; + class IError extends Error { + constructor(opt_error?: string); - NO_SUCH_ELEMENT: number; - NO_SUCH_FRAME: number; - UNKNOWN_COMMAND: number; - UNSUPPORTED_OPERATION: number; // Alias for UNKNOWN_COMMAND. - STALE_ELEMENT_REFERENCE: number; - ELEMENT_NOT_VISIBLE: number; - INVALID_ELEMENT_STATE: number; - UNKNOWN_ERROR: number; - ELEMENT_NOT_SELECTABLE: number; - JAVASCRIPT_ERROR: number; - XPATH_LOOKUP_ERROR: number; - TIMEOUT: number; - NO_SUCH_WINDOW: number; - INVALID_COOKIE_DOMAIN: number; - UNABLE_TO_SET_COOKIE: number; - MODAL_DIALOG_OPENED: number; - UNEXPECTED_ALERT_OPEN: number; - NO_SUCH_ALERT: number; - NO_MODAL_DIALOG_OPEN: number; - SCRIPT_TIMEOUT: number; - INVALID_ELEMENT_COORDINATES: number; - IME_NOT_AVAILABLE: number; - IME_ENGINE_ACTIVATION_FAILED: number; - INVALID_SELECTOR_ERROR: number; - SESSION_NOT_CREATED: number; - MOVE_TARGET_OUT_OF_BOUNDS: number; - SQL_DATABASE_ERROR: number; - INVALID_XPATH_SELECTOR: number; - INVALID_XPATH_SELECTOR_RETURN_TYPE: number; - // The following error codes are derived straight from HTTP return codes. - METHOD_NOT_ALLOWED: number; + code(): number; } - var ErrorCode: IErrorCode; + /** + * The base WebDriver error type. This error type is only used directly when a + * more appropriate category is not defined for the offending error. + */ + class WebDriverError extends IError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } /** - * Error extension that includes error status codes from the WebDriver wire - * protocol: - * http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes - * - * @extends {Error} + * An attempt was made to select an element that cannot be selected. */ - class Error { + class ElementNotSelectableError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Constructors + /** + * An element command could not be completed because the element is not visible + * on the page. + */ + class ElementNotVisibleError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** - * @param {!bot.ErrorCode} code The error's status code. - * @param {string=} opt_message Optional error message. - * @constructor - */ - constructor(code: number, opt_message?: string); + /** + * The arguments passed to a command are either invalid or malformed. + */ + class InvalidArgumentError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //endregion + /** + * An illegal attempt was made to set a cookie under a different domain than + * the current page. + */ + class InvalidCookieDomainError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Static Properties + /** + * The coordinates provided to an interactions operation are invalid. + */ + class InvalidElementCoordinatesError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** - * Status strings enumerated in the W3C WebDriver working draft. - * @enum {string} - * @see http://www.w3.org/TR/webdriver/#status-codes - */ - static State: { - ELEMENT_NOT_SELECTABLE: string; - ELEMENT_NOT_VISIBLE: string; - IME_ENGINE_ACTIVATION_FAILED: string; - IME_NOT_AVAILABLE: string; - INVALID_COOKIE_DOMAIN: string; - INVALID_ELEMENT_COORDINATES: string; - INVALID_ELEMENT_STATE: string; - INVALID_SELECTOR: string; - JAVASCRIPT_ERROR: string; - MOVE_TARGET_OUT_OF_BOUNDS: string; - NO_SUCH_ALERT: string; - NO_SUCH_DOM: string; - NO_SUCH_ELEMENT: string; - NO_SUCH_FRAME: string; - NO_SUCH_WINDOW: string; - SCRIPT_TIMEOUT: string; - SESSION_NOT_CREATED: string; - STALE_ELEMENT_REFERENCE: string; - SUCCESS: string; - TIMEOUT: string; - UNABLE_TO_SET_COOKIE: string; - UNEXPECTED_ALERT_OPEN: string; - UNKNOWN_COMMAND: string; - UNKNOWN_ERROR: string; - UNSUPPORTED_OPERATION: string; - }; + /** + * An element command could not be completed because the element is in an + * invalid state, e.g. attempting to click an element that is no longer attached + * to the document. + */ + class InvalidElementStateError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //endregion + /** + * Argument was an invalid selector. + */ + class InvalidSelectorError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Properties + /** + * Occurs when a command is directed to a session that does not exist. + */ + class NoSuchSessionError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** - * This error's status code. - * @type {!bot.ErrorCode} - */ - code: number; + /** + * An error occurred while executing JavaScript supplied by the user. + */ + class JavascriptError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @type {string} */ - state: string; + /** + * The target for mouse interaction is not in the browser’s viewport and cannot + * be brought into that viewport. + */ + class MoveTargetOutOfBoundsError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @override */ - message: string; + /** + * An attempt was made to operate on a modal dialog when one was not open. + */ + class NoSuchAlertError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @override */ - name: string; + /** + * An element could not be located on the page using the given search + * parameters. + */ + class NoSuchElementError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @override */ - stack: string; + /** + * A request to switch to a frame could not be satisfied because the frame + * could not be found. + */ + class NoSuchFrameError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** - * Flag used for duck-typing when this code is embedded in a Firefox extension. - * This is required since an Error thrown in one component and then reported - * to another will fail instanceof checks in the second component. - * @type {boolean} - */ - isAutomationError: boolean; + /** + * A request to switch to a window could not be satisfied because the window + * could not be found. + */ + class NoSuchWindowError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //endregion + /** + * A script did not complete before its timeout expired. + */ + class ScriptTimeoutError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Methods + /** + * A new session could not be created. + */ + class SessionNotCreatedError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @return {string} The string representation of this error. */ - toString(): string; + /** + * An element command failed because the referenced element is no longer + * attached to the DOM. + */ + class StaleElementReferenceError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //endregion + /** + * An operation did not completErrorCodee before its timeout expired. + */ + class TimeoutError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A request to set a cookie’s value could not be satisfied. + */ + class UnableToSetCookieError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A screen capture operation was not possible. + */ + class UnableToCaptureScreenError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A modal dialog was open, blocking this operation. + */ + class UnexpectedAlertOpenError extends WebDriverError { + /** + * @param {string=} opt_error the error message, if any. + * @param {string=} opt_text the text of the open dialog, if available. + */ + constructor(opt_error?: string, opt_text?: string); + + /** + * @return {(string|undefined)} The text displayed with the unhandled alert, + * if available. + */ + getAlertText(): string; + } + + /** + * A command could not be executed because the remote end is not aware of it. + */ + class UnknownCommandError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The requested command matched a known URL but did not match an method for + * that URL. + */ + class UnknownMethodError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * Reports an unsupport operation. + */ + class UnsupportedOperationError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); } } @@ -776,48 +1736,96 @@ declare namespace webdriver { * @typedef {Object.} */ class Preferences { - setLevel(type: string, level: ILevel): void; + setLevel(type: string|Type, level: Level|string|number): void; toJSON(): { [key: string]: string }; } - interface IType { - /** Logs originating from the browser. */ - BROWSER: string; - /** Logs from a WebDriver client. */ - CLIENT: string; - /** Logs from a WebDriver implementation. */ - DRIVER: string; - /** Logs related to performance. */ - PERFORMANCE: string; - /** Logs from the remote server. */ - SERVER: string; - } - /** * Common log types. * @enum {string} */ - var Type: IType; + enum Type { + /** Logs originating from the browser. */ + BROWSER, + /** Logs from a WebDriver client. */ + CLIENT, + /** Logs from a WebDriver implementation. */ + DRIVER, + /** Logs related to performance. */ + PERFORMANCE, + /** Logs from the remote server. */ + SERVER + } /** - * Logging levels. - * @enum {{value: number, name: webdriver.logging.LevelName}} + * Defines a message level that may be used to control logging output. + * + * @final */ - interface ILevel { - value: number; - name: string; - } + class Level { + name_: string; + value_: number; + /** + * @param {string} name the level's name. + * @param {number} level the level's numeric value. + */ + constructor(name: string, level: number); - interface ILevelValues { - ALL: ILevel; - DEBUG: ILevel; - INFO: ILevel; - WARNING: ILevel; - SEVERE: ILevel; - OFF: ILevel; - } + /** @override */ + toString(): string; - var Level: ILevelValues; + /** This logger's name. */ + name(): string; + + /** The numeric log level. */ + value(): number; + + /** + * Indicates no log messages should be recorded. + * @const + */ + static OFF: Level; + /** + * Log messages with a level of `1000` or higher. + * @const + */ + static SEVERE: Level; + /** + * Log messages with a level of `900` or higher. + * @const + */ + static WARNING: Level; + /** + * Log messages with a level of `800` or higher. + * @const + */ + static INFO: Level; + /** + * Log messages with a level of `700` or higher. + * @const + */ + static DEBUG: Level; + /** + * Log messages with a level of `500` or higher. + * @const + */ + static FINE: Level; + /** + * Log messages with a level of `400` or higher. + * @const + */ + static FINER: Level; + /** + * Log messages with a level of `300` or higher. + * @const + */ + static FINEST: Level; + /** + * Indicates all log messages should be recorded. + * @const + */ + static ALL: Level; + } /** * Converts a level name or value to a {@link webdriver.logging.Level} value. @@ -827,75 +1835,209 @@ declare namespace webdriver { * convert . * @return {!webdriver.logging.Level} The converted level. */ - function getLevel(nameOrValue: string): ILevel; - function getLevel(nameOrValue: number): ILevel; + function getLevel(nameOrValue: string|number): Level; interface IEntryJSON { - level: string; - message: string; - timestamp: number; - type: string; + level: string; + message: string; + timestamp: number; + type: string; } /** * A single log entry. */ class Entry { + /** + * @param {(!webdriver.logging.Level|string)} level The entry level. + * @param {string} message The log message. + * @param {number=} opt_timestamp The time this entry was generated, in + * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the + * current time will be used. + * @param {string=} opt_type The log type, if known. + * @constructor + */ + constructor(level: Level|string|number, message: string, opt_timestamp?:number, opt_type?:string|Type); - //region Constructors + /** @type {!webdriver.logging.Level} */ + level: Level; - /** - * @param {(!webdriver.logging.Level|string)} level The entry level. - * @param {string} message The log message. - * @param {number=} opt_timestamp The time this entry was generated, in - * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the - * current time will be used. - * @param {string=} opt_type The log type, if known. - * @constructor - */ - constructor(level: ILevel, message: string, opt_timestamp?:number, opt_type?:string); - constructor(level: string, message: string, opt_timestamp?:number, opt_type?:string); + /** @type {string} */ + message: string; - //endregion + /** @type {number} */ + timestamp: number; - //region Public Properties + /** @type {string} */ + type: string; - /** @type {!webdriver.logging.Level} */ - level: ILevel; + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): IEntryJSON; + } - /** @type {string} */ - message: string; + /** + * An object used to log debugging messages. Loggers use a hierarchical, + * dot-separated naming scheme. For instance, "foo" is considered the parent of + * the "foo.bar" and an ancestor of "foo.bar.baz". + * + * Each logger may be assigned a {@linkplain #setLevel log level}, which + * controls which level of messages will be reported to the + * {@linkplain #addHandler handlers} attached to this instance. If a log level + * is not explicitly set on a logger, it will inherit its parent. + * + * This class should never be directly instantiated. Instead, users should + * obtain logger references using the {@linkplain ./logging.getLogger() + * getLogger()} function. + * + * @final + */ + class Logger { + /** + * @param {string} name the name of this logger. + * @param {Level=} opt_level the initial level for this logger. + */ + constructor(name: string, opt_level?: Level); - /** @type {number} */ - timestamp: number; + /** @private {string} */ + name_: string; + /** @private {Level} */ + level_: Level; + /** @private {Logger} */ + parent_: Logger; + /** @private {Set} */ + handlers_: any; - /** @type {string} */ - type: string; + /** @return {string} the name of this logger. */ + getName(): string; - //endregion + /** + * @param {Level} level the new level for this logger, or `null` if the logger + * should inherit its level from its parent logger. + */ + setLevel(level: Level): void; - //region Static Methods + /** @return {Level} the log level for this logger. */ + getLevel(): Level; - /** - * Converts a {@link goog.debug.LogRecord} into a - * {@link webdriver.logging.Entry}. - * @param {!goog.debug.LogRecord} logRecord The record to convert. - * @param {string=} opt_type The log type. - * @return {!webdriver.logging.Entry} The converted entry. - */ - static fromClosureLogRecord(logRecord: any, opt_type?:string): Entry; + /** + * @return {!Level} the effective level for this logger. + */ + getEffectiveLevel(): Level; - //endregion + /** + * @param {!Level} level the level to check. + * @return {boolean} whether messages recorded at the given level are loggable + * by this instance. + */ + isLoggable(level: Level): boolean; - //region Methods + /** + * Adds a handler to this logger. The handler will be invoked for each message + * logged with this instance, or any of its descendants. + * + * @param {function(!Entry)} handler the handler to add. + */ + addHandler(handler: any): void; - /** - * @return {{level: string, message: string, timestamp: number, - * type: string}} The JSON representation of this entry. - */ - toJSON(): IEntryJSON; + /** + * Removes a handler from this logger. + * + * @param {function(!Entry)} handler the handler to remove. + * @return {boolean} whether a handler was successfully removed. + */ + removeHandler(handler: any): void; - //endregion + /** + * Logs a message at the given level. The message may be defined as a string + * or as a function that will return the message. If a function is provided, + * it will only be invoked if this logger's + * {@linkplain #getEffectiveLevel() effective log level} includes the given + * `level`. + * + * @param {!Level} level the level at which to log the message. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + log(level: Level, loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.SEVERE} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + severe(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.WARNING} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + warning(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.INFO} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + info(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.DEBUG} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + debug(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.FINE} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + fine(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.FINER} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + finer(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.FINEST} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + finest(loggable: string|Function): void; + } + + /** + * Maintains a collection of loggers. + * + * @final + */ + class LogManager { + /** + * Retrieves a named logger, creating it in the process. This function will + * implicitly create the requested logger, and any of its parents, if they + * do not yet exist. + * + * @param {string} name the logger's name. + * @return {!Logger} the requested logger. + */ + getLogger(name: string): Logger; + + /** + * Creates a new logger. + * + * @param {string} name the logger's name. + * @param {!Logger} parent the logger's parent. + * @return {!Logger} the new logger. + * @private + */ + createLogger_(name: string, parent: Logger): Logger; } } @@ -908,15 +2050,15 @@ declare namespace webdriver { * input array's promises are rejected, the returned promise will be rejected * with the same reason. * - * @param {!Array.<(T|!webdriver.promise.Promise.)>} arr An array of + * @param {!Array<(T|!ManagedPromise)>} arr An array of * promises to wait on. - * @return {!webdriver.promise.Promise.>} A promise that is + * @return {!ManagedPromise>} A promise that is * fulfilled with an array containing the fulfilled values of the * input array, or rejected with the same reason as the first * rejected value. * @template T */ - function all(arr: Promise[]): Promise; + function all(arr: Array>): Promise; /** * Invokes the appropriate callback function as soon as a promised @@ -939,9 +2081,9 @@ declare namespace webdriver { * Creates a new control flow. The provided callback will be invoked as the * first task within the new flow, with the flow as its sole argument. Returns * a promise that resolves to the callback result. - * @param {function(!webdriver.promise.ControlFlow)} callback The entry point + * @param {function(!ControlFlow)} callback The entry point * to the newly created flow. - * @return {!webdriver.promise.Promise} A promise that resolves to the callback + * @return {!ManagedPromise} A promise that resolves to the callback * result. */ function createFlow(callback: (flow: ControlFlow) => R): Promise; @@ -966,7 +2108,7 @@ declare namespace webdriver { * Creates a promise that will be resolved at a set time in the future. * @param {number} ms The amount of time, in milliseconds, to wait before * resolving the promise. - * @return {!webdriver.promise.Promise} The promise. + * @return {!ManagedPromise} The promise. */ function delayed(ms: number): Promise; @@ -974,26 +2116,25 @@ declare namespace webdriver { * Calls a function for each element in an array, and if the function returns * true adds the element to a new array. * - *

If the return value of the filter function is a promise, this function + * If the return value of the filter function is a promise, this function * will wait for it to be fulfilled before determining whether to insert the * element into the new array. * - *

If the filter function throws or returns a rejected promise, the promise + * If the filter function throws or returns a rejected promise, the promise * returned by this function will be rejected with the same reason. Only the * first failure will be reported; all subsequent errors will be silently * ignored. * - * @param {!(Array.|webdriver.promise.Promise.>)} arr The + * @param {!(Array|ManagedPromise>)} arr The * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array.): ( - * boolean|webdriver.promise.Promise.)} fn The function + * @param {function(this: SELF, TYPE, number, !Array): ( + * boolean|ManagedPromise)} fn The function * to call for each element in the array. * @param {SELF=} opt_self The object to be used as the value of 'this' within * {@code fn}. * @template TYPE, SELF */ - function filter(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise; - function filter(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + function filter(arr: Array|Promise>, fn: (element: T, type: any, index: number, array: T[]) => any, opt_self?: any): Promise; /** * Creates a new deferred object. @@ -1003,8 +2144,9 @@ declare namespace webdriver { /** * Creates a promise that has been resolved with the given value. - * @param {*=} opt_value The resolved value. - * @return {!webdriver.promise.Promise} The resolved promise. + * @param {T=} opt_value The resolved value. + * @return {!ManagedPromise} The resolved promise. + * @template T */ function fulfilled(opt_value?: T): Promise; @@ -1013,42 +2155,44 @@ declare namespace webdriver { * new array, which is used as the fulfillment value of the promise returned * by this function. * - *

If the return value of the mapping function is a promise, this function + * If the return value of the mapping function is a promise, this function * will wait for it to be fulfilled before inserting it into the new array. * - *

If the mapping function throws or returns a rejected promise, the + * If the mapping function throws or returns a rejected promise, the * promise returned by this function will be rejected with the same reason. * Only the first failure will be reported; all subsequent errors will be * silently ignored. * - * @param {!(Array.|webdriver.promise.Promise.>)} arr The + * @param {!(Array|ManagedPromise>)} arr The * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array.): ?} fn The + * @param {function(this: SELF, TYPE, number, !Array): ?} fn The * function to call for each element in the array. This function should * expect three arguments (the element, the index, and the array itself. * @param {SELF=} opt_self The object to be used as the value of 'this' within * {@code fn}. * @template TYPE, SELF */ - function map(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise - function map(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + function map(arr: Array|Promise>, fn: (self: any, type: any, index: number, array: any[]) => any, opt_self?: any): Promise /** * Creates a promise that has been rejected with the given reason. * @param {*=} opt_reason The rejection reason; may be any value, but is * usually an Error or a string. - * @return {!webdriver.promise.Promise} The rejected promise. + * @return {!ManagedPromise} The rejected promise. + * @template T */ - function rejected(opt_reason?: any): Promise; + function rejected(opt_reason?: any): Promise; /** - * Wraps a function that is assumed to be a node-style callback as its final - * argument. This callback takes two arguments: an error value (which will be + * Wraps a function that expects a node-style callback as its final + * argument. This callback expects two arguments: an error value (which will be * null if the call succeeded), and the success value as the second argument. - * If the call fails, the returned promise will be rejected, otherwise it will - * be resolved with the result. + * The callback will the resolve or reject the returned promise, based on its + * arguments. * @param {!Function} fn The function to wrap. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * @param {...?} var_args The arguments to apply to the function, excluding the + * final callback. + * @return {!ManagedPromise} A promise that will be resolved with the * result of the provided function's callback. */ function checkedNodeCall(fn: Function, ...var_args: any[]): Promise; @@ -1059,37 +2203,35 @@ declare namespace webdriver { * fulfilled value back into {@code next}. Likewise, if a yielded promise is * rejected, the rejection error will be passed to {@code throw}. * - *

Example 1: the Fibonacci Sequence. - *


-         * webdriver.promise.consume(function* fibonacci() {
-         *   var n1 = 1, n2 = 1;
-         *   for (var i = 0; i < 4; ++i) {
-         *     var tmp = yield n1 + n2;
-         *     n1 = n2;
-         *     n2 = tmp;
-         *   }
-         *   return n1 + n2;
-         * }).then(function(result) {
-         *   console.log(result);  // 13
-         * });
-         * 
+ * __Example 1:__ the Fibonacci Sequence. * - *

Example 2: a generator that throws. - *


-         * webdriver.promise.consume(function* () {
-         *   yield webdriver.promise.delayed(250).then(function() {
-         *     throw Error('boom');
-         *   });
-         * }).thenCatch(function(e) {
-         *   console.log(e.toString());  // Error: boom
-         * });
-         * 
+ * promise.consume(function* fibonacci() { + * var n1 = 1, n2 = 1; + * for (var i = 0; i < 4; ++i) { + * var tmp = yield n1 + n2; + * n1 = n2; + * n2 = tmp; + * } + * return n1 + n2; + * }).then(function(result) { + * console.log(result); // 13 + * }); + * + * __Example 2:__ a generator that throws. + * + * promise.consume(function* () { + * yield promise.delayed(250).then(function() { + * throw Error('boom'); + * }); + * }).catch(function(e) { + * console.log(e.toString()); // Error: boom + * }); * * @param {!Function} generatorFn The generator function to execute. * @param {Object=} opt_self The object to use as "this" when invoking the * initial generator. * @param {...*} var_args Any arguments to pass to the initial generator. - * @return {!webdriver.promise.Promise.} A promise that will resolve to the + * @return {!ManagedPromise} A promise that will resolve to the * generator's final result. * @throws {TypeError} If the given function is not a generator. */ @@ -1104,10 +2246,9 @@ declare namespace webdriver { * resolved successfully. * @param {Function=} opt_errback The function to call when the value is * rejected. - * @return {!webdriver.promise.Promise} A new promise. + * @return {!ManagedPromise} A new promise. */ - function when(value: T, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; - function when(value: Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + function when(value: T|Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; /** * Returns a promise that will be resolved with the input value in a @@ -1120,19 +2261,19 @@ declare namespace webdriver { * Warning: This function makes no checks against objects that contain * cyclical references: * - * var value = {}; - * value['self'] = value; - * webdriver.promise.fullyResolved(value); // Stack overflow. + * var value = {}; + * value['self'] = value; + * promise.fullyResolved(value); // Stack overflow. * * @param {*} value The value to fully resolve. - * @return {!webdriver.promise.Promise} A promise for a fully resolved version + * @return {!ManagedPromise} A promise for a fully resolved version * of the input value. */ function fullyResolved(value: any): Promise; /** * Changes the default flow to use when no others are active. - * @param {!webdriver.promise.ControlFlow} flow The new default flow. + * @param {!ControlFlow} flow The new default flow. * @throws {Error} If the default flow is not currently active. */ function setDefaultFlow(flow: ControlFlow): void; @@ -1141,265 +2282,181 @@ declare namespace webdriver { /** * Error used when the computation of a promise is cancelled. - * - * @extends {goog.debug.Error} - * @final */ - class CancellationError { - /** - * @param {string=} opt_msg The cancellation message. - * @constructor - */ - constructor(opt_msg?: string); - - name: string; - message: string; + class CancellationError extends Error { + /** + * @param {string=} opt_msg The cancellation message. + */ + constructor(opt_msg?: string); } interface IThenable { /** - * Cancels the computation of this promise's value, rejecting the promise in the - * process. This method is a no-op if the promise has alreayd been resolved. + * Cancels the computation of this promise's value, rejecting the promise in + * the process. This method is a no-op if the promise has already been + * resolved. * - * @param {string=} opt_reason The reason this promise is being cancelled. + * @param {(string|Error)=} opt_reason The reason this promise is being + * cancelled. This value will be wrapped in a {@link CancellationError}. */ - cancel(opt_reason?: string): void; - + cancel(opt_reason?: string|Error): void; /** @return {boolean} Whether this promise's value is still being computed. */ isPending(): boolean; - /** * Registers listeners for when this instance is resolved. * - * @param opt_callback The + * @param {?(function(T): (R|IThenable))=} opt_callback The * function to call if this promise is successfully resolved. The function * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be * resolved with the result of the invoked callback. + * @template R */ - then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; - - /** - * Registers listeners for when this instance is resolved. - * - * @param opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be - * resolved with the result of the invoked callback. - */ - then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; - + then(opt_callback?: (value: T) => R|IThenable, opt_errback?: (error: any) => R|IThenable): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous * with the {@code catch} clause in a synchronous API: - *

-             *   // Synchronous API:
-             *   try {
-             *     doSynchronousWork();
-             *   } catch (ex) {
-             *     console.error(ex);
-             *   }
              *
-             *   // Asynchronous promise API:
-             *   doAsynchronousWork().thenCatch(function(ex) {
-             *     console.error(ex);
-             *   });
-             * 
+ * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } * - * @param {function(*): (R|webdriver.promise.Promise.)} errback The function - * to call if this promise is rejected. The function should expect a single - * argument: the rejection reason. - * @return {!webdriver.promise.Promise.} A new promise which will be + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be * resolved with the result of the invoked callback. * @template R */ - thenCatch(errback: (error: any) => any): Promise; - - - /** - * Registers a listener to invoke when this promise is resolved, regardless - * of whether the promise's value was successfully computed. This function - * is synonymous with the {@code finally} clause in a synchronous API: - *

-             *   // Synchronous API:
-             *   try {
-             *     doSynchronousWork();
-             *   } finally {
-             *     cleanUp();
-             *   }
-             *
-             *   // Asynchronous promise API:
-             *   doAsynchronousWork().thenFinally(cleanUp);
-             * 
- * - * Note: similar to the {@code finally} clause, if the registered - * callback returns a rejected promise or throws an error, it will silently - * replace the rejection error (if any) from this promise: - *

-             *   try {
-             *     throw Error('one');
-             *   } finally {
-             *     throw Error('two');  // Hides Error: one
-             *   }
-             *
-             *   webdriver.promise.rejected(Error('one'))
-             *       .thenFinally(function() {
-             *         throw Error('two');  // Hides Error: one
-             *       });
-             * 
- * - * - * @param {function(): (R|webdriver.promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!webdriver.promise.Promise.} A promise that will be fulfilled - * with the callback result. - * @template R - */ - thenFinally(callback: () => any): Promise; + catch(errback: Function): Promise; } /** - * Thenable is a promise-like object with a {@code then} method which may be - * used to schedule callbacks on a promised value. - * - * @interface - * @template T - */ + * Thenable is a promise-like object with a {@code then} method which may be + * used to schedule callbacks on a promised value. + * + * @interface + * @template T + */ class Thenable implements IThenable { /** - * Cancels the computation of this promise's value, rejecting the promise in the - * process. This method is a no-op if the promise has alreayd been resolved. + * Cancels the computation of this promise's value, rejecting the promise in + * the process. This method is a no-op if the promise has already been + * resolved. * - * @param {string=} opt_reason The reason this promise is being cancelled. + * @param {(string|Error)=} opt_reason The reason this promise is being + * cancelled. This value will be wrapped in a {@link CancellationError}. */ - cancel(opt_reason?: string): void; - + cancel(opt_reason?: string|Error): void; /** @return {boolean} Whether this promise's value is still being computed. */ isPending(): boolean; - /** * Registers listeners for when this instance is resolved. * - * @param opt_callback The + * @param {?(function(T): (R|IThenable))=} opt_callback The * function to call if this promise is successfully resolved. The function * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be * resolved with the result of the invoked callback. + * @template R */ - then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; - - /** - * Registers listeners for when this instance is resolved. - * - * @param opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be - * resolved with the result of the invoked callback. - */ - then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; - + then(opt_callback?: (value: T) => R|IThenable, opt_errback?: (error: any) => R|IThenable): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous * with the {@code catch} clause in a synchronous API: - *

-             *   // Synchronous API:
-             *   try {
-             *     doSynchronousWork();
-             *   } catch (ex) {
-             *     console.error(ex);
-             *   }
              *
-             *   // Asynchronous promise API:
-             *   doAsynchronousWork().thenCatch(function(ex) {
-             *     console.error(ex);
-             *   });
-             * 
+ * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } * - * @param {function(*): (R|webdriver.promise.Promise.)} errback The function - * to call if this promise is rejected. The function should expect a single - * argument: the rejection reason. - * @return {!webdriver.promise.Promise.} A new promise which will be + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be * resolved with the result of the invoked callback. * @template R */ - thenCatch(errback: (error: any) => any): Promise; - + catch(errback: Function): Promise; /** * Registers a listener to invoke when this promise is resolved, regardless * of whether the promise's value was successfully computed. This function * is synonymous with the {@code finally} clause in a synchronous API: - *

-             *   // Synchronous API:
-             *   try {
-             *     doSynchronousWork();
-             *   } finally {
-             *     cleanUp();
-             *   }
              *
-             *   // Asynchronous promise API:
-             *   doAsynchronousWork().thenFinally(cleanUp);
-             * 
+ * // Synchronous API: + * try { + * doSynchronousWork(); + * } finally { + * cleanUp(); + * } * - * Note: similar to the {@code finally} clause, if the registered + * // Asynchronous promise API: + * doAsynchronousWork().finally(cleanUp); + * + * __Note:__ similar to the {@code finally} clause, if the registered * callback returns a rejected promise or throws an error, it will silently * replace the rejection error (if any) from this promise: - *

-             *   try {
-             *     throw Error('one');
-             *   } finally {
-             *     throw Error('two');  // Hides Error: one
-             *   }
              *
-             *   webdriver.promise.rejected(Error('one'))
-             *       .thenFinally(function() {
-             *         throw Error('two');  // Hides Error: one
-             *       });
-             * 
+ * try { + * throw Error('one'); + * } finally { + * throw Error('two'); // Hides Error: one + * } * + * promise.rejected(Error('one')) + * .finally(function() { + * throw Error('two'); // Hides Error: one + * }); * - * @param {function(): (R|webdriver.promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * @param {function(): (R|IThenable)} callback The function to call when + * this promise is resolved. + * @return {!ManagedPromise} A promise that will be fulfilled * with the callback result. * @template R */ - thenFinally(callback: () => any): Promise; + finally(callback: Function): Promise; /** * Adds a property to a class prototype to allow runtime checks of whether - * instances of that class implement the Thenable interface. This function will - * also ensure the prototype's {@code then} function is exported from compiled - * code. - * @param {function(new: webdriver.promise.Thenable, ...[?])} ctor The + * instances of that class implement the Thenable interface. This function + * will also ensure the prototype's {@code then} function is exported from + * compiled code. + * @param {function(new: Thenable, ...?)} ctor The * constructor whose prototype to modify. */ static addImplementation(ctor: Function): void; - /** - * Checks if an object has been tagged for implementing the Thenable interface - * as defined by {@link webdriver.promise.Thenable.addImplementation}. + * Checks if an object has been tagged for implementing the Thenable + * interface as defined by {@link Thenable.addImplementation}. * @param {*} object The object to test. * @return {boolean} Whether the object is an implementation of the Thenable * interface. @@ -1432,12 +2489,11 @@ declare namespace webdriver { * function((T|IThenable|Thenable)=), * function(*=))} resolver * Function that is invoked immediately to begin computation of this - * promise's value. The function should accept a pair of callback functions, - * one for fulfilling the promise and another for rejecting it. - * @param {promise.ControlFlow=} opt_flow The control flow + * promise's value. The function should accept a pair of callback + * functions, one for fulfilling the promise and another for rejecting it. + * @param {ControlFlow=} opt_flow The control flow * this instance was created under. Defaults to the currently active flow. - * @constructor - */ + */ constructor(resolver: (onFulfilled: IFulfilledCallback, onRejected: IRejectedCallback)=>void, opt_flow?: ControlFlow); constructor(); // For angular-protractor/angular-protractor-tests.ts @@ -1450,7 +2506,7 @@ declare namespace webdriver { * {@code Error}, one will be created using the value's string * representation. */ - cancel(reason: any): void; + cancel(opt_reason?: string|Error): void; /** @return {boolean} Whether this promise's value is still being computed. */ isPending(): boolean; @@ -1468,23 +2524,7 @@ declare namespace webdriver { * @return A new promise which will be resolved * with the result of the invoked callback. */ - then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; - - /** - * Registers listeners for when this instance is resolved. This function most - * overridden by subtypes. - * - * @param opt_callback The function to call if this promise is - * successfully resolved. The function should expect a single argument: the - * promise's resolved value. - * @param opt_errback The function to call if this promise is - * rejected. The function should expect a single argument: the rejection - * reason. - * @return A new promise which will be resolved - * with the result of the invoked callback. - */ - then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; - + then(opt_callback?: Function, opt_errback?: Function): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous @@ -1512,6 +2552,31 @@ declare namespace webdriver { */ thenCatch(errback: (error: any) => any): Promise; + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): Promise; + /** * Registers a listener to invoke when this promise is resolved, regardless @@ -1552,7 +2617,7 @@ declare namespace webdriver { * with the callback result. * @template R */ - thenFinally(callback: () => any): Promise; + thenFinally(callback: Function): Promise; //endregion } @@ -1791,107 +2856,6 @@ declare namespace webdriver { } } - namespace stacktrace { - /** - * Class representing one stack frame. - */ - class Frame { - /** - * @param {(string|undefined)} context Context object, empty in case of global - * functions or if the browser doesn't provide this information. - * @param {(string|undefined)} name Function name, empty in case of anonymous - * functions. - * @param {(string|undefined)} alias Alias of the function if available. For - * example the function name will be 'c' and the alias will be 'b' if the - * function is defined as a.b = function c() {};. - * @param {(string|undefined)} path File path or URL including line number and - * optionally column number separated by colons. - * @constructor - */ - constructor(context?: string, name?: string, alias?: string, path?: string); - - /** - * @return {string} The function name or empty string if the function is - * anonymous and the object field which it's assigned to is unknown. - */ - getName(): string; - - - /** - * @return {string} The url or empty string if it is unknown. - */ - getUrl(): string; - - - /** - * @return {number} The line number if known or -1 if it is unknown. - */ - getLine(): number; - - - /** - * @return {number} The column number if known and -1 if it is unknown. - */ - getColumn(): number; - - - /** - * @return {boolean} Whether the stack frame contains an anonymous function. - */ - isAnonymous(): boolean; - - - /** - * Converts this frame to its string representation using V8's stack trace - * format: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi - * @return {string} The string representation of this frame. - * @override - */ - toString(): string; - } - - /** - * Stores a snapshot of the stack trace at the time this instance was created. - * The stack trace will always be adjusted to exclude this function call. - */ - class Snapshot { - /** - * @param {number=} opt_slice The number of frames to remove from the top of - * the generated stack trace. - * @constructor - */ - constructor(opt_slice?: number); - - /** - * @return {!Array.} The parsed stack trace. - */ - getStacktrace(): Frame[]; - } - - /** - * Formats an error's stack trace. - * @param {!(Error|goog.testing.JsUnitException)} error The error to format. - * @return {!(Error|goog.testing.JsUnitException)} The formatted error. - */ - function format(error: any): any; - - /** - * Gets the native stack trace if available otherwise follows the call chain. - * The generated trace will exclude all frames up to and including the call to - * this function. - * @return {!Array.} The frames of the stack trace. - */ - function get(): Frame[]; - - /** - * Whether the current browser supports stack traces. - * - * @type {boolean} - * @const - */ - var BROWSER_SUPPORTED: boolean; - } - namespace until { /** * Defines a condition to @@ -1915,32 +2879,31 @@ declare namespace webdriver { /** * Creates a condition that will wait until the input driver is able to switch - * to the designated frame. The target frame may be specified as: - *
    - *
  1. A numeric index into {@code window.frames} for the currently selected - * frame. - *
  2. A {@link webdriver.WebElement}, which must reference a FRAME or IFRAME - * element on the current page. - *
  3. A locator which may be used to first locate a FRAME or IFRAME on the - * current page before attempting to switch to it. - *
+ * to the designated frame. The target frame may be specified as * - *

Upon successful resolution of this condition, the driver will be left + * 1. a numeric index into + * [window.frames](https://developer.mozilla.org/en-US/docs/Web/API/Window.frames) + * for the currently selected frame. + * 2. a {@link ./webdriver.WebElement}, which must reference a FRAME or IFRAME + * element on the current page. + * 3. a locator which may be used to first locate a FRAME or IFRAME on the + * current page before attempting to switch to it. + * + * Upon successful resolution of this condition, the driver will be left * focused on the new frame. * - * @param {!(number|webdriver.WebElement| - * webdriver.Locator|webdriver.By.Hash| - * function(!webdriver.WebDriver): !webdriver.WebElement)} frame + * @param {!(number|./webdriver.WebElement|By| + * function(!./webdriver.WebDriver): !./webdriver.WebElement)} frame * The frame identifier. - * @return {!until.Condition.} A new condition. + * @return {!Condition} A new condition. */ - function ableToSwitchToFrame(frame: number|WebElement|Locator|By.Hash|((webdriver: WebDriver)=>WebElement)): Condition; + function ableToSwitchToFrame(frame: number|WebElement|By|((webdriver: WebDriver)=>WebElement)): Condition; /** * Creates a condition that waits for an alert to be opened. Upon success, the * returned promise will be fulfilled with the handle for the opened alert. * - * @return {!until.Condition.} The new condition. + * @return {!Condition} The new condition. */ function alertIsPresent(): Condition; @@ -2000,13 +2963,12 @@ declare namespace webdriver { /** * Creates a condition that will loop until an element is - * {@link webdriver.WebDriver#findElement found} with the given locator. + * {@link ./webdriver.WebDriver#findElement found} with the given locator. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * to use. + * @param {!(By|Function)} locator The locator to use. * @return {!until.Condition.} The new condition. */ - function elementLocated(locator: Locator|By.Hash|Function): Condition; + function elementLocated(locator: By|Function): Condition; /** * Creates a condition that will wait for the given element's @@ -2039,7 +3001,7 @@ declare namespace webdriver { * * @param {!webdriver.WebElement} element The element to test. * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. * @see webdriver.WebDriver#getText */ function elementTextMatches(element: WebElement, regex: RegExp): Condition; @@ -2053,7 +3015,7 @@ declare namespace webdriver { * @return {!until.Condition.>} The new * condition. */ - function elementsLocated(locator: Locator|By.Hash|Function): Condition; + function elementsLocated(locator: By|Function): Condition; /** * Creates a condition that will wait for the given element to become stale. An @@ -2061,7 +3023,7 @@ declare namespace webdriver { * has loaded. * * @param {!webdriver.WebElement} element The element that should become stale. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. */ function stalenessOf(element: WebElement): Condition; @@ -2080,7 +3042,7 @@ declare namespace webdriver { * given value. * * @param {string} title The expected page title. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. */ function titleIs(title: string): Condition; @@ -2105,18 +3067,18 @@ declare namespace webdriver { } /** - * Enumeration of the buttons used in the advanced interactions API. - * NOTE: A TypeScript enum was not used so that this class could be extended in Protractor. - * @enum {number} + * Representations of pressable keys that aren't text. These are stored in + * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to + * http://www.google.com.au/search?&q=unicode+pua&btnG=Search + * + * @enum {string} */ - interface IButton { - LEFT: number; - MIDDLE: number; - RIGHT: number; + enum Button { + LEFT, + MIDDLE, + RIGHT, } - var Button: IButton; - /** * Representations of pressable keys that aren't text. These are stored in * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to @@ -2124,102 +3086,86 @@ declare namespace webdriver { * * @enum {string} */ - interface IKey { - NULL: string; - CANCEL: string; // ^break - HELP: string; - BACK_SPACE: string; - TAB: string; - CLEAR: string; - RETURN: string; - ENTER: string; - SHIFT: string; - CONTROL: string; - ALT: string; - PAUSE: string; - ESCAPE: string; - SPACE: string; - PAGE_UP: string; - PAGE_DOWN: string; - END: string; - HOME: string; - ARROW_LEFT: string; - LEFT: string; - ARROW_UP: string; - UP: string; - ARROW_RIGHT: string; - RIGHT: string; - ARROW_DOWN: string; - DOWN: string; - INSERT: string; - DELETE: string; - SEMICOLON: string; - EQUALS: string; + enum Key { + NULL, + CANCEL, // ^break + HELP, + BACK_SPACE, + TAB, + CLEAR, + RETURN, + ENTER, + SHIFT, + CONTROL, + ALT, + PAUSE, + ESCAPE, + SPACE, + PAGE_UP, + PAGE_DOWN, + END, + HOME, + ARROW_LEFT, + LEFT, + ARROW_UP, + UP, + ARROW_RIGHT, + RIGHT, + ARROW_DOWN, + DOWN, + INSERT, + DELETE, + SEMICOLON, + EQUALS, - NUMPAD0: string; // number pad keys - NUMPAD1: string; - NUMPAD2: string; - NUMPAD3: string; - NUMPAD4: string; - NUMPAD5: string; - NUMPAD6: string; - NUMPAD7: string; - NUMPAD8: string; - NUMPAD9: string; - MULTIPLY: string; - ADD: string; - SEPARATOR: string; - SUBTRACT: string; - DECIMAL: string; - DIVIDE: string; + NUMPAD0, // number pad keys + NUMPAD1, + NUMPAD2, + NUMPAD3, + NUMPAD4, + NUMPAD5, + NUMPAD6, + NUMPAD7, + NUMPAD8, + NUMPAD9, + MULTIPLY, + ADD, + SEPARATOR, + SUBTRACT, + DECIMAL, + DIVIDE, - F1: string; // function keys - F2: string; - F3: string; - F4: string; - F5: string; - F6: string; - F7: string; - F8: string; - F9: string; - F10: string; - F11: string; - F12: string; + F1, // function keys + F2, + F3, + F4, + F5, + F6, + F7, + F8, + F9, + F10, + F11, + F12, - COMMAND: string; // Apple command key - META: string; // alias for Windows key + COMMAND, // Apple command key + META // alias for Windows key - /** - * Simulate pressing many keys at once in a "chord". Takes a sequence of - * {@link webdriver.Key}s or strings, appends each of the values to a string, - * and adds the chord termination key ({@link webdriver.Key.NULL}) and returns - * the resultant string. - * - * Note: when the low-level webdriver key handlers see Keys.NULL, active - * modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event. - * - * @param {...string} var_args The key sequence to concatenate. - * @return {string} The null-terminated key sequence. - * @see http://code.google.com/p/webdriver/issues/detail?id=79 - */ - chord: (...var_args: string[]) => string; } - var Key: IKey; - /** * Class for defining sequences of complex user interactions. Each sequence * will not be executed until {@link #perform} is called. * - *

Example:


-     *   new webdriver.ActionSequence(driver).
-     *       keyDown(webdriver.Key.SHIFT).
-     *       click(element1).
-     *       click(element2).
-     *       dragAndDrop(element3, element4).
-     *       keyUp(webdriver.Key.SHIFT).
-     *       perform();
-     * 
+ * Example: + * + * new ActionSequence(driver). + * keyDown(Key.SHIFT). + * click(element1). + * click(element2). + * dragAndDrop(element3, element4). + * keyUp(Key.SHIFT). + * perform(); * */ class ActionSequence { @@ -2247,14 +3193,18 @@ declare namespace webdriver { * Moves the mouse. The location to move to may be specified in terms of the * mouse's current location, an offset relative to the top-left corner of an * element, or an element (in which case the middle of the element is used). - * @param {(!webdriver.WebElement|{x: number, y: number})} location The - * location to drag to, as either another WebElement or an offset in pixels. - * @param {{x: number, y: number}=} opt_offset An optional offset, in pixels. - * Defaults to (0, 0). - * @return {!webdriver.ActionSequence} A self reference. + * + * @param {(!./webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, as either another WebElement or an offset in + * pixels. + * @param {{x: number, y: number}=} opt_offset If the target {@code location} + * is defined as a {@link ./webdriver.WebElement}, this parameter defines + * an offset within that element. The offset should be specified in pixels + * relative to the top-left corner of the element's bounding box. If + * omitted, the element's center will be used as the target offset. + * @return {!ActionSequence} A self reference. */ - mouseMove(location: WebElement, opt_offset?: ILocation): ActionSequence; - mouseMove(location: ILocation): ActionSequence; + mouseMove(location: WebElement|ILocation, opt_offset?: ILocation): ActionSequence; /** * Presses a mouse button. The mouse button will not be released until @@ -2262,100 +3212,101 @@ declare namespace webdriver { * sequence or another. The behavior for out-of-order events (e.g. mouseDown, * click) is undefined. * - *

If an element is provided, the mouse will first be moved to the center + * If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: - *

sequence.mouseMove(element).mouseDown()
* - *

Warning: this method currently only supports the left mouse button. See - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).mouseDown() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - mouseDown(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - mouseDown(opt_elementOrButton?: number): ActionSequence; + mouseDown(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Releases a mouse button. Behavior is undefined for calling this function * without a previous call to {@link #mouseDown}. * - *

If an element is provided, the mouse will first be moved to the center + * If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: - *

sequence.mouseMove(element).mouseUp()
* - *

Warning: this method currently only supports the left mouse button. See - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).mouseUp() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - mouseUp(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - mouseUp(opt_elementOrButton?: number): ActionSequence; + mouseUp(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Convenience function for performing a "drag and drop" manuever. The target * element may be moved to the location of another element, or by an offset (in * pixels). - * @param {!webdriver.WebElement} element The element to drag. - * @param {(!webdriver.WebElement|{x: number, y: number})} location The - * location to drag to, either as another WebElement or an offset in pixels. - * @return {!webdriver.ActionSequence} A self reference. + * + * @param {!./webdriver.WebElement} element The element to drag. + * @param {(!./webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, either as another WebElement or an offset in + * pixels. + * @return {!ActionSequence} A self reference. */ - dragAndDrop(element: WebElement, location: WebElement): ActionSequence; - dragAndDrop(element: WebElement, location: ILocation): ActionSequence; + dragAndDrop(element: WebElement, location: WebElement|ILocation): ActionSequence; /** * Clicks a mouse button. * - *

If an element is provided, the mouse will first be moved to the center + * If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: - *

sequence.mouseMove(element).click()
* - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * sequence.mouseMove(element).click() + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - click(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - click(opt_elementOrButton?: number): ActionSequence; + click(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Double-clicks a mouse button. * - *

If an element is provided, the mouse will first be moved to the center of + * If an element is provided, the mouse will first be moved to the center of * that element. This is equivalent to: - *

sequence.mouseMove(element).doubleClick()
* - *

Warning: this method currently only supports the left mouse button. See - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).doubleClick() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - doubleClick(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - doubleClick(opt_elementOrButton?: number): ActionSequence; + doubleClick(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Performs a modifier key press. The modifier key is not released @@ -2366,7 +3317,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - keyDown(key: string): ActionSequence; + keyDown(key: Key): ActionSequence; /** * Performs a modifier key release. The release is targetted at the currently @@ -2376,7 +3327,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - keyUp(key: string): ActionSequence; + keyUp(key: Key): ActionSequence; /** * Simulates typing multiple keys. Each modifier key encountered in the @@ -2387,7 +3338,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - sendKeys(...var_args: any[]): ActionSequence; + sendKeys(...var_args: Array): ActionSequence; //endregion } @@ -2483,7 +3434,6 @@ declare namespace webdriver { */ scroll(offset: IOffset): TouchSequence; - /** * Scrolls the touch screen, starting on `elem` and moving by the specified * offset. @@ -2494,7 +3444,6 @@ declare namespace webdriver { */ scrollFromElement(elem: WebElement, offset: IOffset): TouchSequence; - /** * Flick, starting anywhere on the screen, at speed xspeed and yspeed. * @@ -2504,7 +3453,6 @@ declare namespace webdriver { */ flick(speed: ISpeed): TouchSequence; - /** * Flick starting at elem and moving by x and y at specified speed. * @@ -2516,26 +3464,29 @@ declare namespace webdriver { flickElement(elem: WebElement, offset: IOffset, speed: number): TouchSequence; } - interface IOffset { x: number; y: number; } - interface ISpeed { xspeed: number; yspeed: number; } - /** * Represents a modal dialog such as {@code alert}, {@code confirm}, or * {@code prompt}. Provides functions to retrieve the message displayed with * the alert, accept or dismiss the alert, and set the response text (in the * case of {@code prompt}). */ - interface Alert { + class Alert { + /** + * @param {!WebDriver} driver The driver controlling the browser this alert + * is attached to. + * @param {string} text The message text displayed with this alert. + */ + constructor(driver: WebDriver, text: string); //region Methods @@ -2547,6 +3498,18 @@ declare namespace webdriver { */ getText(): webdriver.promise.Promise; + /** + * Sets the username and password in an alert prompting for credentials (such + * as a Basic HTTP Auth prompt). This method will implicitly + * {@linkplain #accept() submit} the dialog. + * + * @param {string} username The username to send. + * @param {string} password The password to send. + * @return {!promise.Promise} A promise that will be resolved when this + * command has completed. + */ + authenticateAs(username: string, password: string): webdriver.promise.Promise; + /** * Accepts this alert. * @return {!webdriver.promise.Promise} A promise that will be resolved when @@ -2580,47 +3543,149 @@ declare namespace webdriver { * serves as a forward proxy on an Alert, allowing calls to be scheduled * directly on this instance before the underlying Alert has been fulfilled. In * other words, the following two statements are equivalent: - *


+     *
      *     driver.switchTo().alert().dismiss();
      *     driver.switchTo().alert().then(function(alert) {
      *       return alert.dismiss();
      *     });
-     * 
* - * @param {!webdriver.WebDriver} driver The driver controlling the browser this - * alert is attached to. - * @param {!webdriver.promise.Thenable.} alert A thenable - * that will be fulfilled with the promised alert. - * @constructor - * @extends {webdriver.Alert} - * @implements {webdriver.promise.Thenable.} + * @implements {promise.Thenable.} * @final */ - interface AlertPromise extends Alert, webdriver.promise.IThenable { + class AlertPromise extends Alert implements webdriver.promise.IThenable{ + /** + * @param {!WebDriver} driver The driver controlling the browser this + * alert is attached to. + * @param {!promise.Thenable} alert A thenable + * that will be fulfilled with the promised alert. + */ + constructor(driver: WebDriver, alert: webdriver.promise.Promise); + + //region Methods + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. + * @param {*} reason The reason this promise is being cancelled. If not an + * {@code Error}, one will be created using the value's string + * representation. + */ + cancel(opt_reason?: string|Error): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. This function most + * overridden by subtypes. + * + * @param opt_callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param opt_errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @return A new promise which will be resolved + * with the result of the invoked callback. + */ + then(opt_callback?: Function, opt_errback?: Function): webdriver.promise.Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *

+             *   // Synchronous API:
+             *   try {
+             *     doSynchronousWork();
+             *   } catch (ex) {
+             *     console.error(ex);
+             *   }
+             *
+             *   // Asynchronous promise API:
+             *   doAsynchronousWork().thenCatch(function(ex) {
+             *     console.error(ex);
+             *   });
+             * 
+ * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): webdriver.promise.Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): webdriver.promise.Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *

+             *   // Synchronous API:
+             *   try {
+             *     doSynchronousWork();
+             *   } finally {
+             *     cleanUp();
+             *   }
+             *
+             *   // Asynchronous promise API:
+             *   doAsynchronousWork().thenFinally(cleanUp);
+             * 
+ * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *

+             *   try {
+             *     throw Error('one');
+             *   } finally {
+             *     throw Error('two');  // Hides Error: one
+             *   }
+             *
+             *   webdriver.promise.rejected(Error('one'))
+             *       .thenFinally(function() {
+             *         throw Error('two');  // Hides Error: one
+             *       });
+             * 
+ * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: Function): webdriver.promise.Promise; } - /** - * An error returned to indicate that there is an unhandled modal dialog on the - * current page. - * @extends {bot.Error} - */ - interface UnhandledAlertError extends webdriver.error.Error { - //region Methods - - /** - * @return {string} The text displayed with the unhandled alert. - */ - getAlertText(): string; - - /** - * @return {!webdriver.Alert} The open alert. - * @deprecated Use {@link #getAlertText}. This method will be removed in - * 2.45.0. - */ - getAlert(): Alert; - - - //endregion + /** @deprecated Use {@link error.UnexpectedAlertOpenError} instead. */ + class UnhandledAlertError extends webdriver.error.UnexpectedAlertOpenError { } /** @@ -2630,7 +3695,9 @@ declare namespace webdriver { interface IBrowser { ANDROID: string; CHROME: string; + EDGE: string; FIREFOX: string; + IE: string; INTERNET_EXPLORER: string; IPAD: string; IPHONE: string; @@ -2651,6 +3718,45 @@ declare namespace webdriver { noProxy?: string; } + /** + * Creates new {@link webdriver.WebDriver WebDriver} instances. The environment + * variables listed below may be used to override a builder's configuration, + * allowing quick runtime changes. + * + * - {@code SELENIUM_BROWSER}: defines the target browser in the form + * {@code browser[:version][:platform]}. + * + * - {@code SELENIUM_REMOTE_URL}: defines the remote URL for all builder + * instances. This environment variable should be set to a fully qualified + * URL for a WebDriver server (e.g. http://localhost:4444/wd/hub). This + * option always takes precedence over {@code SELENIUM_SERVER_JAR}. + * + * - {@code SELENIUM_SERVER_JAR}: defines the path to the + * + * standalone Selenium server jar to use. The server will be started the + * first time a WebDriver instance and be killed when the process exits. + * + * Suppose you had mytest.js that created WebDriver with + * + * var driver = new webdriver.Builder() + * .forBrowser('chrome') + * .build(); + * + * This test could be made to use Firefox on the local machine by running with + * `SELENIUM_BROWSER=firefox node mytest.js`. Rather than change the code to + * target Google Chrome on a remote machine, you can simply set the + * `SELENIUM_BROWSER` and `SELENIUM_REMOTE_URL` environment variables: + * + * SELENIUM_BROWSER=chrome:36:LINUX \ + * SELENIUM_REMOTE_URL=http://www.example.com:4444/wd/hub \ + * node mytest.js + * + * You could also use a local copy of the standalone Selenium server: + * + * SELENIUM_BROWSER=chrome:36:LINUX \ + * SELENIUM_SERVER_JAR=/path/to/selenium-server-standalone.jar \ + * node mytest.js + */ class Builder { //region Constructors @@ -2664,15 +3770,45 @@ declare namespace webdriver { //region Methods + /** + * Configures this builder to ignore any environment variable overrides and to + * only use the configuration specified through this instance's API. + * + * @return {!Builder} A self reference. + */ + disableEnvironmentOverrides(): Builder; + /** * Creates a new WebDriver client based on this builder's current * configuration. * + * While this method will immediately return a new WebDriver instance, any + * commands issued against it will be deferred until the associated browser + * has been fully initialized. Users may call {@link #buildAsync()} to obtain + * a promise that will not be fulfilled until the browser has been created + * (the difference is purely in style). + * * @return {!webdriver.WebDriver} A new WebDriver instance. * @throws {Error} If the current configuration is invalid. + * @see #buildAsync() */ build(): WebDriver; + /** + * Creates a new WebDriver client based on this builder's current + * configuration. This method returns a promise that will not be fulfilled + * until the new browser session has been fully initialized. + * + * __Note:__ this method is purely a convenience wrapper around + * {@link #build()}. + * + * @return {!promise.Promise} A promise that will be + * fulfilled with the newly created WebDriver instance once the browser + * has been fully initialized. + * @see #build() + */ + buildAsync(): webdriver.promise.Promise; + /** * Configures the target browser for clients created by this instance. * Any calls to {@link #withCapabilities} after this function will @@ -2705,6 +3841,12 @@ declare namespace webdriver { */ getServerUrl(): string; + /** + * @return {?string} The URL of the proxy server to use for the WebDriver's + * HTTP connections, or `null` if not set. + */ + getWebDriverProxy(): string; + /** * Sets the default action to take with an unexpected alert before returning * an error. @@ -2735,6 +3877,17 @@ declare namespace webdriver { */ setControlFlow(flow: webdriver.promise.ControlFlow): Builder; + /** + * Set {@linkplain edge.Options options} specific to Microsoft's Edge browser + * for drivers created by this builder. Any proxy settings defined on the + * given options will take precedence over those set through + * {@link #setProxy}. + * + * @param {!edge.Options} options The MicrosoftEdgeDriver options to use. + * @return {!Builder} A self reference. + */ + setEdgeOptions(options: edge.Options): Builder; + /** * Sets whether native events should be used. * @param {boolean} enabled Whether to enable native events. @@ -2753,6 +3906,16 @@ declare namespace webdriver { */ setFirefoxOptions(options: firefox.Options): Builder; + /** + * Set Internet Explorer specific {@linkplain ie.Options options} for drivers + * created by this builder. Any proxy settings defined on the given options + * will take precedence over those set through {@link #setProxy}. + * + * @param {!ie.Options} options The IEDriver options to use. + * @return {!Builder} A self reference. + */ + setIeOptions(options: ie.Options): Builder; + /** * Sets the logging preferences for the created session. Preferences may be * changed by repeated calls, or by calling {@link #withCapabilities}. @@ -2760,17 +3923,37 @@ declare namespace webdriver { * desired logging preferences. * @return {!Builder} A self reference. */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Builder; - setLoggingPrefs(prefs: { [key: string]: string }): Builder; + setLoggingPrefs(prefs: webdriver.logging.Preferences|Object): Builder; + + /** + * Sets Opera specific {@linkplain opera.Options options} for drivers created + * by this builder. Any logging or proxy settings defined on the given options + * will take precedence over those set through {@link #setLoggingPrefs} and + * {@link #setProxy}, respectively. + * + * @param {!opera.Options} options The OperaDriver options to use. + * @return {!Builder} A self reference. + */ + setOperaOptions(options: opera.Options): Builder; /** * Sets the proxy configuration to use for WebDriver clients created by this * builder. Any calls to {@link #withCapabilities} after this function will * overwrite these settings. - * @param {!webdriver.ProxyConfig} config The configuration to use. + * @param {!capabilities.ProxyConfig} config The configuration to use. * @return {!Builder} A self reference. */ - setProxy(config: ProxyConfig): Builder; + setProxy(config: webdriver.ProxyConfig): Builder; + + /** + * Sets Safari specific {@linkplain safari.Options options} for drivers + * created by this builder. Any logging settings defined on the given options + * will take precedence over those set through {@link #setLoggingPrefs}. + * + * @param {!safari.Options} options The Safari options to use. + * @return {!Builder} A self reference. + */ + setSafari(options: safari.Options): Builder; /** * Sets how elements should be scrolled into view for interaction. @@ -2793,6 +3976,16 @@ declare namespace webdriver { */ usingServer(url: string): Builder; + /** + * Sets the URL of the proxy to use for the WebDriver's HTTP connections. + * If this method is never called, the Builder will create a connection + * without a proxy. + * + * @param {string} proxy The URL of a proxy to use. + * @return {!Builder} A self reference. + */ + usingWebDriverProxy(proxy: string): Builder; + /** * Sets the desired capabilities when requesting a new session. This will * overwrite any previously set capabilities. @@ -2800,12 +3993,149 @@ declare namespace webdriver { * capabilities for a new session. * @return {!Builder} A self reference. */ - withCapabilities(capabilities: Capabilities): Builder; - withCapabilities(capabilities: any): Builder; + withCapabilities(capabilities: Object|Capabilities): Builder; //endregion } + /** + * Describes a mechanism for locating an element on the page. + * @final + */ + class By { + + /** + * @param {string} using the name of the location strategy to use. + * @param {string} value the value to search for. + */ + constructor(using: string, value: string); + + /** + * Locates elements that have a specific class name. + * + * @param {string} name The class name to search for. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes + * @see http://www.w3.org/TR/CSS2/selector.html#class-html + */ + static className(name: string): By; + + /** + * Locates elements using a CSS selector. + * + * @param {string} selector The CSS selector to use. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/CSS2/selector.html + */ + static css(selector: string): By; + + /** + * Locates eleemnts by the ID attribute. This locator uses the CSS selector + * `*[id="$ID"]`, _not_ `document.getElementById`. + * + * @param {string} id The ID to search for. + * @return {!By} The new locator. + */ + static id(id: string): By; + + /** + * Locates link elements whose + * {@linkplain webdriver.WebElement#getText visible text} matches the given + * string. + * + * @param {string} text The link text to search for. + * @return {!By} The new locator. + */ + static linkText(text: string): By; + + /** + * Locates an elements by evaluating a + * {@linkplain webdriver.WebDriver#executeScript JavaScript expression}. + * The result of this expression must be an element or list of elements. + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {function(!./webdriver.WebDriver): !./promise.Promise} + * A new JavaScript-based locator function. + */ + static js(script: string|Function, ...var_args: Array): (webdriver: webdriver.WebDriver) => webdriver.promise.Promise; + + /** + * Locates elements whose `name` attribute has the given value. + * + * @param {string} name The name attribute to search for. + * @return {!By} The new locator. + */ + static name(name: string): By; + + /** + * Locates link elements whose + * {@linkplain webdriver.WebElement#getText visible text} contains the given + * substring. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!By} The new locator. + */ + static partialLinkText(text: string): By; + + /** + * Locates elements with a given tag name. + * + * @param {string} name The tag name to search for. + * @return {!By} The new locator. + * @deprecated Use {@link By.css() By.css(tagName)} instead. + */ + static tagName(name: string): By; + + /** + * Locates elements matching a XPath selector. Care should be taken when + * using an XPath selector with a {@link webdriver.WebElement} as WebDriver + * will respect the context in the specified in the selector. For example, + * given the selector `//div`, WebDriver will search from the document root + * regardless of whether the locator was used with a WebElement. + * + * @param {string} xpath The XPath selector to use. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/xpath/ + */ + static xpath(xpath: string): By; + + /** @override */ + toString(): string; + } + + /** + * Short-hand expressions for the primary element locator strategies. + * For example the following two statements are equivalent: + * + * var e1 = driver.findElement(webdriver.By.id('foo')); + * var e2 = driver.findElement({id: 'foo'}); + * + * Care should be taken when using JavaScript minifiers (such as the + * Closure compiler), as locator hashes will always be parsed using + * the un-obfuscated properties listed. + * + * @typedef {( + * {className: string}| + * {css: string}| + * {id: string}| + * {js: string}| + * {linkText: string}| + * {name: string}| + * {partialLinkText: string}| + * {tagName: string}| + * {xpath: string})} + */ + type ByHash = {className: string}| + {css: string}| + {id: string}| + {js: string}| + {linkText: string}| + {name: string}| + {partialLinkText: string}| + {tagName: string}| + {xpath: string}; + /** * Common webdriver capability keys. * @enum {string} @@ -2876,7 +4206,7 @@ declare namespace webdriver { SECURE_SSL: string; /** Whether the driver supports manipulating the app cache. */ - SUPPORTS_APPLICATION_CACHE: string; + SUPPORTS_APPLICATION_CACHE: string; /** Whether the driver supports locating elements with CSS selectors. */ SUPPORTS_CSS_SELECTORS: string; @@ -2910,8 +4240,7 @@ declare namespace webdriver { * capabilities to merge into this instance. * @constructor */ - constructor(opt_other?: Capabilities); - constructor(opt_other?: any); + constructor(opt_other?: Capabilities|Object); //endregion @@ -2927,8 +4256,7 @@ declare namespace webdriver { * merge into this instance. * @return {!webdriver.Capabilities} A self reference. */ - merge(other: Capabilities): Capabilities; - merge(other: any): Capabilities; + merge(other: Capabilities|Object): Capabilities; /** * @param {string} key The capability to set. @@ -2946,9 +4274,7 @@ declare namespace webdriver { * logging preferences. * @return {!webdriver.Capabilities} A self reference. */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Capabilities; - setLoggingPrefs(prefs: { [key: string]: string }): Capabilities; - + setLoggingPrefs(prefs: webdriver.logging.Preferences|Object): Capabilities; /** * Sets the proxy configuration for this instance. @@ -3010,6 +4336,11 @@ declare namespace webdriver { */ static chrome(): Capabilities; + /** + * @return {!Capabilities} A basic set of capabilities for Microsoft Edge. + */ + static edge(): Capabilities; + /** * @return {!webdriver.Capabilities} A basic set of capabilities for Firefox. */ @@ -3183,6 +4514,8 @@ declare namespace webdriver { GET_AVAILABLE_LOG_TYPES: string; GET_LOG: string; GET_SESSION_LOGS: string; + + UPLOAD_FILE: string; } var CommandName: ICommandName; @@ -3241,19 +4574,47 @@ declare namespace webdriver { } /** - * Handles the execution of {@code webdriver.Command} objects. + * Handles the execution of WebDriver {@link Command commands}. + * @interface */ - interface CommandExecutor { - /** - * Executes the given {@code command}. If there is an error executing the - * command, the provided callback will be invoked with the offending error. - * Otherwise, the callback will be invoked with a null Error and non-null - * {@link bot.response.ResponseObject} object. - * @param {!webdriver.Command} command The command to execute. - * @param {function(Error, !bot.response.ResponseObject=)} callback the function - * to invoke when the command response is ready. - */ - execute(command: Command, callback: (error: Error, responseObject: any) => any ): void; + class Executor { + /** + * Executes the given {@code command}. If there is an error executing the + * command, the provided callback will be invoked with the offending error. + * Otherwise, the callback will be invoked with a null Error and non-null + * response object. + * + * @param {!Command} command The command to execute. + * @return {!promise.Promise} A promise that will be fulfilled with + * the command result. + */ + execute(command: Command): webdriver.promise.Promise + } + + /** + * Wraps a promised {@link Executor}, ensuring no commands are executed until + * the wrapped executor has been fully resolved. + * @implements {Executor} + */ + class DeferredExecutor { + /** + * @param {!promise.Promise} delegate The promised delegate, which + * may be provided by any promise-like thenable object. + */ + constructor(delegate: webdriver.promise.Promise); + } + + /** + * Describes an event listener registered on an {@linkplain EventEmitter}. + */ + class Listener { + /** + * @param {!Function} fn The acutal listener function. + * @param {(Object|undefined)} scope The object in whose scope to invoke the + * listener. + * @param {boolean} oneshot Whether this listener should only be used once. + */ + constructor(fn: Function, scope: Object, oneshot: boolean); } /** @@ -3283,39 +4644,42 @@ declare namespace webdriver { /** * Returns a mutable list of listeners for a specific type of event. * @param {string} type The type of event to retrieve the listeners for. - * @return {!Array.<{fn: !Function, oneshot: boolean, - * scope: (Object|undefined)}>} The registered listeners for - * the given event type. + * @return {!Set} The registered listeners for the given event + * type. */ - listeners(type: string): Array<{fn: Function; oneshot: boolean; scope: any;}>; + listeners(type: string): any; /** * Registers a listener. * @param {string} type The type of event to listen for. - * @param {!Function} listenerFn The function to invoke when the event is fired. - * @param {Object=} opt_scope The object in whose scope to invoke the listener. - * @return {!webdriver.EventEmitter} A self reference. + * @param {!Function} fn The function to invoke when the event is fired. + * @param {Object=} opt_self The object in whose scope to invoke the listener. + * @param {boolean=} opt_oneshot Whether the listener should b (e removed after + * the first event is fired. + * @return {!EventEmitter} A self reference. + * @private */ - addListener(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; + addListener(type: string, fn: Function, opt_scope?:any, opt_oneshot?: boolean): EventEmitter; + /** * Registers a one-time listener which will be called only the first time an * event is emitted, after which it will be removed. * @param {string} type The type of event to listen for. - * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {!Function} fn The function to invoke when the event is fired. * @param {Object=} opt_scope The object in whose scope to invoke the listener. * @return {!webdriver.EventEmitter} A self reference. */ - once(type: string, listenerFn: any, opt_scope?: any): EventEmitter; + once(type: string, fn: any, opt_scope?: any): EventEmitter; /** * An alias for {@code #addListener()}. * @param {string} type The type of event to listen for. - * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {!Function} fn The function to invoke when the event is fired. * @param {Object=} opt_scope The object in whose scope to invoke the listener. * @return {!webdriver.EventEmitter} A self reference. */ - on(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; + on(type: string, fn: Function, opt_scope?:any): EventEmitter; /** * Removes a previously registered event listener. @@ -3340,14 +4704,20 @@ declare namespace webdriver { /** * Interface for navigating back and forth in the browser history. */ - interface WebDriverNavigation { + class Navigation { //region Constructors /** - * @param {!webdriver.WebDriver} driver The parent driver. - * @constructor + * Interface for navigating back and forth in the browser history. + * + * This class should never be instantiated directly. Insead, obtain an instance + * with + * + * webdriver.navigate() + * + * @see WebDriver#navigate() */ - new (driver: WebDriver): WebDriverNavigation; + constructor(driver: WebDriver); //endregion @@ -3397,14 +4767,14 @@ declare namespace webdriver { /** * Provides methods for managing browser and driver state. */ - interface WebDriverOptions { + class Options { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: webdriver.WebDriver): WebDriverOptions; + constructor(driver: webdriver.WebDriver); //endregion @@ -3417,13 +4787,13 @@ declare namespace webdriver { * @param {string=} opt_path The cookie path. * @param {string=} opt_domain The cookie domain. * @param {boolean=} opt_isSecure Whether the cookie is secure. - * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified as - * a number, should be in milliseconds since midnight, January 1, 1970 UTC. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * cookie has been added to the page. + * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified + * as a number, should be in milliseconds since midnight, + * January 1, 1970 UTC. + * @return {!promise.Promise} A promise that will be resolved + * when the cookie has been added to the page. */ - addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number): webdriver.promise.Promise; - addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: Date): webdriver.promise.Promise; + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number|Date): webdriver.promise.Promise; /** * Schedules a command to delete all cookies visible to the current page. @@ -3467,19 +4837,19 @@ declare namespace webdriver { * @return {!webdriver.WebDriver.Logs} The interface for managing driver * logs. */ - logs(): WebDriverLogs; + logs(): webdriver.Logs; /** * @return {!webdriver.WebDriver.Timeouts} The interface for managing driver * timeouts. */ - timeouts(): WebDriverTimeouts; + timeouts(): webdriver.Timeouts; /** * @return {!webdriver.WebDriver.Window} The interface for managing the * current window. */ - window(): WebDriverWindow; + window(): webdriver.Window; //endregion } @@ -3487,14 +4857,14 @@ declare namespace webdriver { /** * An interface for managing timeout behavior for WebDriver instances. */ - interface WebDriverTimeouts { + class Timeouts { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverTimeouts; + constructor(driver: webdriver.WebDriver); //endregion @@ -3549,7 +4919,7 @@ declare namespace webdriver { /** * An interface for managing the current window. */ - interface WebDriverWindow { + class Window { //region Constructors @@ -3557,7 +4927,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverWindow; + constructor(driver: webdriver.WebDriver); //endregion @@ -3612,7 +4982,7 @@ declare namespace webdriver { /** * Interface for managing WebDriver log records. */ - interface WebDriverLogs { + class Logs { //region Constructors @@ -3620,7 +4990,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverLogs; + constructor(driver: webdriver.WebDriver); //endregion @@ -3640,7 +5010,7 @@ declare namespace webdriver { * promise that will resolve to a list of log entries for the specified * type. */ - get(type: string): webdriver.promise.Promise; + get(type: webdriver.logging.Type): webdriver.promise.Promise; /** * Retrieves the log types available to this driver. @@ -3655,7 +5025,7 @@ declare namespace webdriver { /** * An interface for changing the focus of the driver to another frame or window. */ - interface WebDriverTargetLocator { + class TargetLocator { //region Constructors @@ -3663,7 +5033,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverTargetLocator; + constructor(driver: webdriver.WebDriver); //endregion @@ -3687,44 +5057,47 @@ declare namespace webdriver { /** * Schedules a command to switch the focus of all future commands to another - * frame on the page. - *

- * If the frame is specified by a number, the command will switch to the frame - * by its (zero-based) index into the {@code window.frames} collection. - *

- * If the frame is specified by a string, the command will select the frame by - * its name or ID. To select sub-frames, simply separate the frame names/IDs by - * dots. As an example, "main.child" will select the frame with the name "main" - * and then its child "child". - *

- * If the specified frame can not be found, the deferred result will errback - * with a {@code bot.ErrorCode.NO_SUCH_FRAME} error. - * @param {string|number} nameOrIndex The frame locator. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * driver has changed focus to the specified frame. + * frame on the page. The target frame may be specified as one of the + * following: + * + * - A number that specifies a (zero-based) index into [window.frames]( + * https://developer.mozilla.org/en-US/docs/Web/API/Window.frames). + * - A {@link WebElement} reference, which correspond to a `frame` or `iframe` + * DOM element. + * - The `null` value, to select the topmost frame on the page. Passing `null` + * is the same as calling {@link #defaultContent defaultContent()}. + * + * If the specified frame can not be found, the returned promise will be + * rejected with a {@linkplain error.NoSuchFrameError}. + * + * @param {(number|WebElement|null)} id The frame locator. + * @return {!promise.Promise} A promise that will be resolved + * when the driver has changed focus to the specified frame. */ - frame(nameOrIndex: string): webdriver.promise.Promise; - frame(nameOrIndex: number): webdriver.promise.Promise; + frame(nameOrIndex: number|WebElement): webdriver.promise.Promise; /** * Schedules a command to switch the focus of all future commands to another * window. Windows may be specified by their {@code window.name} attribute or - * by its handle (as returned by {@code webdriver.WebDriver#getWindowHandles}). - *

- * If the specificed window can not be found, the deferred result will errback - * with a {@code bot.ErrorCode.NO_SUCH_WINDOW} error. + * by its handle (as returned by {@link WebDriver#getWindowHandles}). + * + * If the specified window cannot be found, the returned promise will be + * rejected with a {@linkplain error.NoSuchWindowError}. + * * @param {string} nameOrHandle The name or window handle of the window to * switch focus to. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * driver has changed focus to the specified window. + * @return {!promise.Promise} A promise that will be resolved + * when the driver has changed focus to the specified window. */ window(nameOrHandle: string): webdriver.promise.Promise; /** - * Schedules a command to change focus to the active alert dialog. This command - * will return a {@link bot.ErrorCode.NO_MODAL_DIALOG_OPEN} error if a modal - * dialog is not currently open. - * @return {!webdriver.Alert} The open alert. + * Schedules a command to change focus to the active modal dialog, such as + * those opened by `window.alert()`, `window.confirm()`, and + * `window.prompt()`. The returned promise will be rejected with a + * {@linkplain error.NoSuchAlertError} if there are no open alerts. + * + * @return {!AlertPromise} The open alert. */ alert(): AlertPromise; @@ -3789,27 +5162,14 @@ declare namespace webdriver { //region Constructors /** - * @param {!(webdriver.Session|webdriver.promise.Promise)} session Either a + * @param {!(Session|promise.Promise)} session Either a * known session or a promise that will be resolved to a session. - * @param {!webdriver.CommandExecutor} executor The executor to use when - * sending commands to the browser. - * @param {webdriver.promise.ControlFlow=} opt_flow The flow to + * @param {!command.Executor} executor The executor to use when sending + * commands to the browser. + * @param {promise.ControlFlow=} opt_flow The flow to * schedule commands through. Defaults to the active flow object. - * @constructor */ - constructor(session: Session, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); - constructor(session: webdriver.promise.Promise, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); - - //endregion - - //region Static Properties - - static Navigation: WebDriverNavigation; - static Options: WebDriverOptions; - static Timeouts: WebDriverTimeouts; - static Window: WebDriverWindow; - static Logs: WebDriverLogs; - static TargetLocator: WebDriverTargetLocator; + constructor(session: Session|webdriver.promise.Promise, executor: Executor, opt_flow?: webdriver.promise.ControlFlow); //endregion @@ -3817,29 +5177,29 @@ declare namespace webdriver { /** * Creates a new WebDriver client for an existing session. - * @param {!webdriver.CommandExecutor} executor Command executor to use when - * querying for session details. + * @param {!command.Executor} executor Command executor to use when querying + * for session details. * @param {string} sessionId ID of the session to attach to. - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver - * commands should execute under. Defaults to the - * {@link webdriver.promise.controlFlow() currently active} control flow. - * @return {!webdriver.WebDriver} A new client for the specified session. + * @param {promise.ControlFlow=} opt_flow The control flow all + * driver commands should execute under. Defaults to the + * {@link promise.controlFlow() currently active} control flow. + * @return {!WebDriver} A new client for the specified session. */ - static attachToSession(executor: CommandExecutor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + static attachToSession(executor: Executor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; /** * Creates a new WebDriver session. - * @param {!webdriver.CommandExecutor} executor The executor to create the new - * session with. - * @param {!webdriver.Capabilities} desiredCapabilities The desired + * @param {!command.Executor} executor The executor to create the new session + * with. + * @param {!./capabilities.Capabilities} desiredCapabilities The desired * capabilities for the new session. - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver + * @param {promise.ControlFlow=} opt_flow The control flow all driver * commands should execute under, including the initial session creation. - * Defaults to the {@link webdriver.promise.controlFlow() currently active} + * Defaults to the {@link promise.controlFlow() currently active} * control flow. - * @return {!webdriver.WebDriver} The driver for the newly created session. + * @return {!WebDriver} The driver for the newly created session. */ - static createSession(executor: CommandExecutor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + static createSession(executor: Executor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; //endregion @@ -3852,20 +5212,22 @@ declare namespace webdriver { controlFlow(): webdriver.promise.ControlFlow; /** - * Schedules a {@code webdriver.Command} to be executed by this driver's - * {@code webdriver.CommandExecutor}. - * @param {!webdriver.Command} command The command to schedule. + * Schedules a {@link command.Command} to be executed by this driver's + * {@link command.Executor}. + * + * @param {!command.Command} command The command to schedule. * @param {string} description A description of the command for debugging. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * the command result. + * @return {!promise.Promise} A promise that will be resolved + * with the command result. + * @template T */ schedule(command: Command, description: string): webdriver.promise.Promise; /** - * Sets the {@linkplain webdriver.FileDetector file detector} that should be + * Sets the {@linkplain input.FileDetector file detector} that should be * used with this instance. - * @param {webdriver.FileDetector} detector The detector to use or {@code null}. + * @param {input.FileDetector} detector The detector to use or {@code null}. */ setFileDetector(detector: FileDetector): void; @@ -3895,23 +5257,23 @@ declare namespace webdriver { /** * Creates a new action sequence using this driver. The sequence will not be - * scheduled for execution until {@link webdriver.ActionSequence#perform} is + * scheduled for execution until {@link actions.ActionSequence#perform} is * called. Example: - *


-         *   driver.actions().
-         *       mouseDown(element1).
-         *       mouseMove(element2).
-         *       mouseUp().
-         *       perform();
-         * 
- * @return {!webdriver.ActionSequence} A new action sequence for this instance. + * + * driver.actions(). + * mouseDown(element1). + * mouseMove(element2). + * mouseUp(). + * perform(); + * + * @return {!actions.ActionSequence} A new action sequence for this instance. */ actions(): ActionSequence; /** * Creates a new touch sequence using this driver. The sequence will not be - * scheduled for execution until {@link webdriver.TouchSequence#perform} is + * scheduled for execution until {@link actions.TouchSequence#perform} is * called. Example: * * driver.touchActions(). @@ -3919,7 +5281,7 @@ declare namespace webdriver { * doubleTap(element2). * perform(); * - * @return {!webdriver.TouchSequence} A new touch sequence for this instance. + * @return {!actions.TouchSequence} A new touch sequence for this instance. */ touchActions(): TouchSequence; @@ -3961,8 +5323,7 @@ declare namespace webdriver { * scripts return value. * @template T */ - executeScript(script: string, ...var_args: any[]): webdriver.promise.Promise; - executeScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; + executeScript(script: string|Function, ...var_args: any[]): webdriver.promise.Promise; /** * Schedules a command to execute asynchronous JavaScript in the context of the @@ -4179,38 +5540,27 @@ declare namespace webdriver { * var e1 = driver.findElement(By.id('foo')); * var e2 = driver.findElement({id:'foo'}); * - * You may also provide a custom locator function, which takes as input - * this WebDriver instance and returns a {@link webdriver.WebElement}, or a - * promise that will resolve to a WebElement. For example, to find the first - * visible link on a page, you could write: + * You may also provide a custom locator function, which takes as input this + * instance and returns a {@link WebElement}, or a promise that will resolve + * to a WebElement. If the returned promise resolves to an array of + * WebElements, WebDriver will use the first element. For example, to find the + * first visible link on a page, you could write: * * var link = driver.findElement(firstVisibleLink); * * function firstVisibleLink(driver) { * var links = driver.findElements(By.tagName('a')); - * return webdriver.promise.filter(links, function(link) { - * return links.isDisplayed(); - * }).then(function(visibleLinks) { - * return visibleLinks[0]; + * return promise.filter(links, function(link) { + * return link.isDisplayed(); * }); * } * - * 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. - * - * @param {!(webdriver.Locator|webdriver.By.Hash|Element|Function)} locator The - * locator to use. - * @return {!webdriver.WebElement} A WebElement that can be used to issue + * @param {!(by.By|Function)} locator The locator to use. + * @return {!WebElementPromise} 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. */ - findElement(locatorOrElement: Locator|By.Hash|WebElement|Function): WebElementPromise; + findElement(locator: By|Function): WebElementPromise; /** * Schedules a command to test if an element is present on the page. @@ -4219,35 +5569,36 @@ declare namespace webdriver { * 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. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Element| - * Function)} locatorOrElement The locator to use, or the actual - * DOM element to be located by the server. - * @return {!webdriver.promise.Promise.} A promise that will resolve + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise} A promise that will resolve * with whether the element is present on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * driver.findElements(locator).then(e => !!e.length); */ - isElementPresent(locatorOrElement: Locator|By.Hash|WebElement|Function): webdriver.promise.Promise; + isElementPresent(locatorOrElement: By|Function): webdriver.promise.Promise; /** * Schedule a command to search for multiple elements on the page. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * strategy to use when searching for the element. - * @return {!webdriver.promise.Promise.>} A + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + findElements(locator: By|Function): webdriver.promise.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 - *
* - * @return {!webdriver.promise.Promise.} A promise that will be + * 1. Entire page + * 2. Current window + * 3. Visible portion of the current frame + * 4. The entire display containing the browser + * + * @return {!promise.Promise} A promise that will be * resolved to the screenshot as a base-64 encoded PNG. */ takeScreenshot(): webdriver.promise.Promise; @@ -4256,45 +5607,25 @@ declare namespace webdriver { * @return {!webdriver.WebDriver.Options} The options interface for this * instance. */ - manage(): WebDriverOptions; + manage(): webdriver.Options; /** * @return {!webdriver.WebDriver.Navigation} The navigation interface for this * instance. */ - navigate(): WebDriverNavigation; + navigate(): Navigation; /** * @return {!webdriver.WebDriver.TargetLocator} The target locator interface for * this instance. */ - switchTo(): WebDriverTargetLocator; + switchTo(): webdriver.TargetLocator; //endregion } interface IWebElementId { - ELEMENT: string; - } - - /** - * Defines an object that can be asynchronously serialized to its WebDriver - * wire representation. - * - * @constructor - * @template T - */ - interface Serializable { - /** - * Returns either this instance's serialized represention, if immediately - * available, or a promise for its serialized representation. This function is - * conceptually equivalent to objects that have a {@code toJSON()} property, - * except the serialize() result may be a promise or an object containing a - * promise (which are not directly JSON friendly). - * - * @return {!(T|IThenable.)} This instance's serialized wire format. - */ - serialize(): T|webdriver.promise.IThenable; + [ELEMENT:string]: string; } /** @@ -4554,7 +5885,7 @@ declare namespace webdriver { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: Locator|By.Hash|Function): WebElementPromise; + findElement(locator: By|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this @@ -4565,7 +5896,7 @@ declare namespace webdriver { * @return {!webdriver.promise.Promise.} A promise that will be * resolved with whether an element could be located on the page. */ - isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + isElementPresent(locator: By|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that @@ -4576,10 +5907,9 @@ declare namespace webdriver { * @return {!webdriver.promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + findElements(locator: By|Function): webdriver.promise.Promise; } - /** * Defines an object that can be asynchronously serialized to its WebDriver * wire representation. @@ -4600,7 +5930,6 @@ declare namespace webdriver { serialize(): T|webdriver.promise.IThenable; } - /** * Represents a DOM element. WebElements can be found by searching from the * document root using a {@link webdriver.WebDriver} instance, or by searching @@ -4626,35 +5955,59 @@ declare namespace webdriver { */ class WebElement implements Serializable { /** - * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this - * element. - * @param {!(webdriver.promise.Promise.| - * webdriver.WebElement.Id)} id The server-assigned opaque ID for the - * underlying DOM element. - * @constructor + * @param {!WebDriver} driver the parent WebDriver instance for this element. + * @param {(!IThenable|string)} id The server-assigned opaque ID for + * the underlying DOM element. */ - constructor(driver: WebDriver, id: webdriver.promise.Promise|IWebElementId); + constructor(driver: webdriver.WebDriver, id: webdriver.promise.Promise|string); /** - * Wire protocol definition of a WebElement ID. - * @typedef {{ELEMENT: string}} - * @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol + * @param {string} id The raw ID. + * @param {boolean=} opt_noLegacy Whether to exclude the legacy element key. + * @return {!Object} The element ID for use with WebDriver's wire protocol. */ - static Id: IWebElementId; + static buildId(id: string, opt_noLegacy?: boolean): Object; /** - * The property key used in the wire protocol to indicate that a JSON object - * contains the ID of a WebElement. - * @type {string} - * @const + * Extracts the encoded WebElement ID from the object. + * + * @param {?} obj The object to extract the ID from. + * @return {string} the extracted ID. + * @throws {TypeError} if the object is not a valid encoded ID. */ - static ELEMENT_KEY: string; + static extractId(obj: IWebElementId): string; + /** + * @param {?} obj the object to test. + * @return {boolean} whether the object is a valid encoded WebElement ID. + */ + static isId(obj: IWebElementId): boolean; + + /** + * Compares two WebElements for equality. + * + * @param {!WebElement} a A WebElement. + * @param {!WebElement} b A WebElement. + * @return {!promise.Promise} A promise that will be + * resolved to whether the two WebElements are equal. + */ + static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; /** * @return {!webdriver.WebDriver} The parent driver for this instance. */ - getDriver(): WebDriver; + getDriver(): webdriver.WebDriver; + + /** + * @return {!promise.Promise} A promise that resolves to + * the server-assigned opaque ID assigned to this element. + */ + getId(): webdriver.promise.Promise; + + /** + * @deprecated Use {@link #getId()} instead. + */ + getRawId(): any; /** * Schedule a command to find a descendant of this element. If the element @@ -4688,35 +6041,40 @@ declare namespace webdriver { * }); * } * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the element. - * @return {!webdriver.WebElement} A WebElement that can be used to issue + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!WebElementPromise} 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. */ - findElement(locator: Locator|By.Hash|Function): WebElementPromise; + findElement(locator: By|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this * element that matches the given search criteria. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the element. - * @return {!webdriver.promise.Promise.} A promise that will be + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise} A promise that will be * resolved with whether an element could be located on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * element.findElements(locator).then(e => !!e.length); */ - isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + isElementPresent(locator: By|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that * match the given search criteria. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the elements. - * @return {!webdriver.promise.Promise.>} A + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + findElements(locator: By|Function): webdriver.promise.Promise; /** * Schedules a command to click on this element. @@ -4727,7 +6085,7 @@ declare namespace webdriver { /** * Schedules a command to type a sequence on the DOM element represented by this - * instance. + * promsieinstance. * * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is * processed in the keysequence, that key state is toggled until one of the @@ -4799,7 +6157,7 @@ declare namespace webdriver { * * @param {string} cssStyleProperty The name of the CSS style property to look * up. - * @return {!webdriver.promise.Promise.} A promise that will be + * @return {!promise.Promise} A promise that will be * resolved with the requested CSS value. */ getCssValue(cssStyleProperty: string): webdriver.promise.Promise; @@ -4885,10 +6243,10 @@ declare namespace webdriver { submit(): webdriver.promise.Promise; /** - * Schedules a command to clear the {@code value} of this element. This command - * has no effect if the underlying DOM element is neither a text INPUT element + * Schedules a command to clear the `value` of this element. This command has + * no effect if the underlying DOM element is neither a text INPUT element * nor a TEXTAREA element. - * @return {!webdriver.promise.Promise.} A promise that will be resolved + * @return {!promise.Promise} A promise that will be resolved * when the element has been cleared. */ clear(): webdriver.promise.Promise; @@ -4900,6 +6258,18 @@ declare namespace webdriver { */ isDisplayed(): webdriver.promise.Promise; + /** + * Take a screenshot of the visible region encompassed by this element's + * bounding rectangle. + * + * @param {boolean=} opt_scroll Optional argument that indicates whether the + * element should be scrolled into view before taking a screenshot. + * Defaults to false. + * @return {!promise.Promise} A promise that will be + * resolved to the screenshot as a base-64 encoded PNG. + */ + takeScreenshot(opt_scroll?: boolean): webdriver.promise.Promise; + /** * Schedules a command to retrieve the outer HTML of this element. * @return {!webdriver.promise.Promise.} A promise that will be @@ -4907,25 +6277,6 @@ declare namespace webdriver { */ getOuterHtml(): webdriver.promise.Promise; - /** - * @return {!webdriver.promise.Promise.} A promise - * that resolves to this element's JSON representation as defined by the - * WebDriver wire protocol. - * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol - */ - getId(): webdriver.promise.Promise; - - /** - * Returns the raw ID string ID for this element. - * @return {!webdriver.promise.Promise} A promise that resolves to this - * element's raw ID as a string value. - * @package - */ - getRawId(): webdriver.promise.Promise; - - /** @override */ - serialize(): webdriver.promise.Promise; - /** * Schedules a command to retrieve the inner HTML of this element. * @return {!webdriver.promise.Promise} A promise that will be resolved with the @@ -4933,14 +6284,8 @@ declare namespace webdriver { */ getInnerHtml(): webdriver.promise.Promise; - /** - * Compares to WebElements for equality. - * @param {!webdriver.WebElement} a A WebElement. - * @param {!webdriver.WebElement} b A WebElement. - * @return {!webdriver.promise.Promise} A promise that will be resolved to - * whether the two WebElements are equal. - */ - static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; + /** @override */ + serialize(): webdriver.promise.Promise; } /** @@ -4966,6 +6311,14 @@ declare namespace webdriver { * @final */ class WebElementPromise extends WebElement implements webdriver.promise.IThenable { + /** + * @param {!WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!promise.Promise} el A promise + * that will resolve to the promised element. + */ + constructor(driver: webdriver.WebDriver, el: webdriver.promise.Promise); + /** * Cancels the computation of this promise's value, rejecting the promise in the * process. This method is a no-op if the promise has alreayd been resolved. @@ -5075,191 +6428,31 @@ declare namespace webdriver { * @template R */ thenFinally(callback: () => any): webdriver.promise.Promise; - } - namespace By { /** - * Locates elements that have a specific class name. The returned locator - * is equivalent to searching for elements with the CSS selector ".clazz". + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: * - * @param {string} className The class name to search for. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes - * @see http://www.w3.org/TR/CSS2/selector.html#class-html - */ - function className(value: string): Locator; - - /** - * Locates elements using a CSS selector. For browsers that do not support - * CSS selectors, WebDriver implementations may return an - * {@linkplain bot.Error.State.INVALID_SELECTOR invalid selector} error. An - * implementation may, however, emulate the CSS selector API. + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } * - * @param {string} selector The CSS selector to use. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/CSS2/selector.html - */ - function css(value: string): Locator; - - /** - * Locates an element by its ID. + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); * - * @param {string} id The ID to search for. - * @return {!webdriver.Locator} The new locator. + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R */ - function id(value: string): Locator; - - /** - * Locates link elements whose {@linkplain webdriver.WebElement#getText visible - * text} matches the given string. - * - * @param {string} text The link text to search for. - * @return {!webdriver.Locator} The new locator. - */ - function linkText(value: string): Locator; - - /** - * Locates an elements by evaluating a - * {@linkplain webdriver.WebDriver#executeScript JavaScript expression}. - * The result of this expression must be an element or list of elements. - * - * @param {!(string|Function)} script The script to execute. - * @param {...*} var_args The arguments to pass to the script. - * @return {function(!webdriver.WebDriver): !webdriver.promise.Promise} A new, - * JavaScript-based locator function. - */ - function js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; - - /** - * Locates elements whose {@code name} attribute has the given value. - * - * @param {string} name The name attribute to search for. - * @return {!webdriver.Locator} The new locator. - */ - function name(value: string): Locator; - - /** - * Locates link elements whose {@linkplain webdriver.WebElement#getText visible - * text} contains the given substring. - * - * @param {string} text The substring to check for in a link's visible text. - * @return {!webdriver.Locator} The new locator. - */ - function partialLinkText(value: string): Locator; - - /** - * Locates elements with a given tag name. The returned locator is - * equivalent to using the - * [getElementsByTagName](https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName) - * DOM function. - * - * @param {string} text The substring to check for in a link's visible text. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html - */ - function tagName(value: string): Locator; - - /** - * Locates elements matching a XPath selector. Care should be taken when - * using an XPath selector with a {@link webdriver.WebElement} as WebDriver - * will respect the context in the specified in the selector. For example, - * given the selector {@code "//div"}, WebDriver will search from the - * document root regardless of whether the locator was used with a - * WebElement. - * - * @param {string} xpath The XPath selector to use. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/xpath/ - */ - function xpath(value: string): Locator; - - /** - * Short-hand expressions for the primary element locator strategies. - * For example the following two statements are equivalent: - * - * var e1 = driver.findElement(webdriver.By.id('foo')); - * var e2 = driver.findElement({id: 'foo'}); - * - * Care should be taken when using JavaScript minifiers (such as the - * Closure compiler), as locator hashes will always be parsed using - * the un-obfuscated properties listed. - * - * @typedef {( - * {className: string}| - * {css: string}| - * {id: string}| - * {js: string}| - * {linkText: string}| - * {name: string}| - * {partialLinkText: string}| - * {tagName: string}| - * {xpath: string})} - */ - type Hash = {className: string}| - {css: string}| - {id: string}| - {js: string}| - {linkText: string}| - {name: string}| - {partialLinkText: string}| - {tagName: string}| - {xpath: string}; - } - - /** - * An element locator. - */ - class Locator { - /** - * An element locator. - * @param {string} using The type of strategy to use for this locator. - * @param {string} value The search target of this locator. - * @constructor - */ - constructor(using: string, value: string); - - - /** - * Maps {@link webdriver.By.Hash} keys to the appropriate factory function. - * @type {!Object.} - * @const - */ - static Strategy: { - className: typeof webdriver.By.className; - css: typeof webdriver.By.css; - id: typeof webdriver.By.id; - js: typeof webdriver.By.js; - linkText: typeof webdriver.By.linkText; - name: typeof webdriver.By.name; - partialLinkText: typeof webdriver.By.partialLinkText; - tagName: typeof webdriver.By.tagName; - xpath: typeof webdriver.By.xpath; - }; - - /** - * Verifies that a {@code value} is a valid locator to use for searching for - * elements on the page. - * - * @param {*} value The value to check is a valid locator. - * @return {!(webdriver.Locator|Function)} A valid locator object or function. - * @throws {TypeError} If the given value is an invalid locator. - */ - static checkLocator(value: any): Locator | Function; - - /** - * The search strategy to use when searching for an element. - * @type {string} - */ - using: string; - - /** - * The search target for this locator. - * @type {string} - */ - value: string; - - /** @return {string} String representation of this locator. */ - toString(): string; + catch(errback: Function): webdriver.promise.Promise; } /** @@ -5275,8 +6468,7 @@ declare namespace webdriver { * capabilities. * @constructor */ - constructor(id: string, capabilities: Capabilities); - constructor(id: string, capabilities: any); + constructor(id: string, capabilities: Capabilities|Object); //endregion @@ -5290,7 +6482,7 @@ declare namespace webdriver { /** * @return {!webdriver.Capabilities} This session's capabilities. */ - getCapabilities(): Capabilities; + getCapabilities(): webdriver.Capabilities; /** * Retrieves the value of a specific capability. @@ -5376,10 +6568,6 @@ declare module 'selenium-webdriver/chrome' { export = chrome; } -declare module 'selenium-webdriver/firefox' { - export = firefox; -} - declare module 'selenium-webdriver/executors' { export = executors; } diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index da141b8eb3..8833933ad1 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -3,7 +3,7 @@ function TestChromeDriver() { var driver: chrome.Driver = new chrome.Driver(); driver = new chrome.Driver(webdriver.Capabilities.chrome()); - driver = new chrome.Driver(webdriver.Capabilities.chrome(), new webdriver.promise.ControlFlow()); + driver = new chrome.Driver(webdriver.Capabilities.chrome(), new remote.DriverService('executable', new chrome.Options()), new webdriver.promise.ControlFlow()); var baseDriver: webdriver.WebDriver = driver; } @@ -31,7 +31,6 @@ function TestChromeOptions() { options = options.setUserPreferences("preferences"); var capabilities: webdriver.Capabilities = options.toCapabilities(); capabilities = options.toCapabilities(webdriver.Capabilities.chrome()); - var values: chrome.IOptionsValues = options.toJSON(); } function TestServiceBuilder() { @@ -52,7 +51,7 @@ function TestServiceBuilder() { function TestChromeModule() { var service: any = chrome.getDefaultService(); - chrome.setDefaultService({}); + chrome.setDefaultService(new remote.DriverService('executable', new chrome.Options())); } function TestBinary() { @@ -66,8 +65,8 @@ function TestBinary() { function TestFirefoxDriver() { var driver: firefox.Driver = new firefox.Driver(); - driver = new chrome.Driver(webdriver.Capabilities.firefox()); - driver = new chrome.Driver(webdriver.Capabilities.firefox(), new webdriver.promise.ControlFlow()); + driver = new firefox.Driver(webdriver.Capabilities.firefox()); + driver = new firefox.Driver(webdriver.Capabilities.firefox(), new webdriver.promise.ControlFlow()); var baseDriver: webdriver.WebDriver = driver; } @@ -82,7 +81,6 @@ function TestFirefoxOptions() { options = options.setProfile(new firefox.Profile()); options = options.setProxy({ proxyType: "proxy" }); var capabilities: webdriver.Capabilities = options.toCapabilities(); - var capabilities: webdriver.Capabilities = options.toCapabilities({}); } function TestFirefoxProfile() { @@ -108,7 +106,7 @@ function TestFirefoxProfile() { } function TestExecutors() { - var exec: webdriver.CommandExecutor = executors.createExecutor("url"); + var exec: webdriver.Executor = executors.createExecutor("url"); var promise: webdriver.promise.Promise; exec = executors.createExecutor(promise); } @@ -144,7 +142,9 @@ function TestActionSequence() { build(); var sequence: webdriver.ActionSequence = new webdriver.ActionSequence(driver); - var element: webdriver.WebElement = new webdriver.WebElement(driver, { ELEMENT: 'id' }); + var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); + var promise: webdriver.promise.Promise; + element = new webdriver.WebElement(driver, promise); // Click sequence = sequence.click(); @@ -187,7 +187,6 @@ function TestActionSequence() { // SendKeys sequence = sequence.sendKeys("A", "B", "C"); - sequence = sequence.sendKeys(["A", "B", "C"]); sequence.perform().then(function () { }); } @@ -196,7 +195,7 @@ function TestTouchSequence() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). build(); - var element: webdriver.WebElement = new webdriver.WebElement(driver, { ELEMENT: 'id' }); + var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); var sequence: webdriver.TouchSequence = new webdriver.TouchSequence(driver); @@ -319,9 +318,9 @@ function TestCommand() { command = command.setParameters({ param: 123 }); } -function TestCommandExecutor() { - var c: webdriver.CommandExecutor = { execute: function (command: webdriver.Command, callback: (error: Error, obj: any) => any) { } }; - c.execute(new webdriver.Command('name'), function (error: Error, response: any) { }); +function TestDeferredExecutor() { + var promise: webdriver.promise.Promise; + var executor: webdriver.DeferredExecutor = new webdriver.DeferredExecutor(promise); } function TestCommandName() { @@ -458,7 +457,7 @@ function TestEventEmitter() { } function TestKey() { - var key: string; + var key: webdriver.Key; key = webdriver.Key.ADD; key = webdriver.Key.ALT; @@ -520,35 +519,15 @@ function TestKey() { key = webdriver.Key.SUBTRACT; key = webdriver.Key.TAB; key = webdriver.Key.UP; - - key = webdriver.Key.chord(webdriver.Key.NUMPAD0, webdriver.Key.NUMPAD1); } -function TestLocator() { +function TestBy() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). build(); - var locator: webdriver.Locator = new webdriver.Locator('class name', 'class'); + var locator: webdriver.By = new webdriver.By('class name', 'class'); - var locatorOrFn: webdriver.Locator|Function; - - locatorOrFn = webdriver.Locator.Strategy.className; - locatorOrFn = webdriver.Locator.Strategy.css; - locatorOrFn = webdriver.Locator.Strategy.id; - locatorOrFn = webdriver.Locator.Strategy.js; - locatorOrFn = webdriver.Locator.Strategy.linkText; - locatorOrFn = webdriver.Locator.Strategy.name; - locatorOrFn = webdriver.Locator.Strategy.partialLinkText; - locatorOrFn = webdriver.Locator.Strategy.tagName; - locatorOrFn = webdriver.Locator.Strategy.xpath; - - locatorOrFn = webdriver.Locator.checkLocator(locator); - locatorOrFn = webdriver.Locator.checkLocator({ className: 'class' }); - locatorOrFn = webdriver.Locator.checkLocator(Error); - - var using: string = locator.using; - var value: string = locator.value; var str: string = locator.toString(); locator = webdriver.By.className('class'); @@ -563,7 +542,7 @@ function TestLocator() { // Can import "By" without import declarations var By = webdriver.By; - var locatorHash: webdriver.By.Hash; + var locatorHash: webdriver.ByHash; locatorHash = { className: 'class' }; locatorHash = { css: 'css' }; locatorHash = { id: 'id' }; @@ -591,9 +570,7 @@ function TestSession() { function TestUnhandledAlertError() { var someFunc = function (error: webdriver.UnhandledAlertError) { - var baseError: webdriver.error.Error = error; - - var alert: webdriver.Alert = error.getAlert(); + var baseError: Error = error; var str: string = error.getAlertText(); str = error.toString(); } @@ -614,7 +591,7 @@ function TestWebDriverLogs() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var logs: webdriver.WebDriverLogs = new webdriver.WebDriver.Logs(driver); + var logs: webdriver.Logs = new webdriver.Logs(driver); logs.get(webdriver.logging.Type.BROWSER).then(function (entries: webdriver.logging.Entry[]) { });; logs.getAvailableLogTypes().then(function (types: string[]) { }); @@ -625,7 +602,7 @@ function TestWebDriverNavigation() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var navigation: webdriver.WebDriverNavigation = new webdriver.WebDriver.Navigation(driver); + var navigation: webdriver.Navigation = new webdriver.Navigation(driver); navigation.back().then(function () { }); navigation.forward().then(function () { }); @@ -638,7 +615,7 @@ function TestWebDriverOptions() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var options: webdriver.WebDriverOptions = new webdriver.WebDriver.Options(driver); + var options: webdriver.Options = new webdriver.Options(driver); var promise: webdriver.promise.Promise; // Add Cookie @@ -654,9 +631,9 @@ function TestWebDriverOptions() { options.getCookie('name').then(function (cookies: webdriver.IWebDriverOptionsCookie) { }); options.getCookies().then(function (cookies: webdriver.IWebDriverOptionsCookie[]) { }); - var logs: webdriver.WebDriverLogs = options.logs(); - var timeouts: webdriver.WebDriverTimeouts = options.timeouts(); - var window: webdriver.WebDriverWindow = options.window(); + var logs: webdriver.Logs = options.logs(); + var timeouts: webdriver.Timeouts = options.timeouts(); + var window: webdriver.Window = options.window(); } function TestWebDriverTargetLocator() { @@ -664,13 +641,12 @@ function TestWebDriverTargetLocator() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var locator: webdriver.WebDriverTargetLocator = new webdriver.WebDriver.TargetLocator(driver); + var locator: webdriver.TargetLocator = new webdriver.TargetLocator(driver); var promise: webdriver.promise.Promise; var element: webdriver.WebElement = locator.activeElement(); var alert: webdriver.Alert = locator.alert(); promise = locator.defaultContent(); - promise = locator.frame('name'); promise = locator.frame(1); promise = locator.window('nameOrHandle'); } @@ -680,7 +656,7 @@ function TestWebDriverTimeouts() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var timeouts: webdriver.WebDriverTimeouts = new webdriver.WebDriver.Timeouts(driver); + var timeouts: webdriver.Timeouts = new webdriver.Timeouts(driver); var promise: webdriver.promise.Promise; promise = timeouts.implicitlyWait(123); @@ -693,7 +669,7 @@ function TestWebDriverWindow() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var window: webdriver.WebDriverWindow = new webdriver.WebDriver.Window(driver); + var window: webdriver.Window = new webdriver.Window(driver); var locationPromise: webdriver.promise.Promise; var sizePromise: webdriver.promise.Promise; var voidPromise: webdriver.promise.Promise; @@ -708,7 +684,7 @@ function TestWebDriverWindow() { function TestWebDriver() { var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); var sessionPromise: webdriver.promise.Promise; - var executor: webdriver.CommandExecutor = executors.createExecutor("http://someserver"); + var executor: webdriver.Executor = executors.createExecutor("http://someserver"); var flow: webdriver.promise.ControlFlow = new webdriver.promise.ControlFlow(); var driver: webdriver.WebDriver = new webdriver.WebDriver(session, executor); driver = new webdriver.WebDriver(session, executor, flow); @@ -746,15 +722,11 @@ function TestWebDriver() { // findElement var element: webdriver.WebElement; element = driver.findElement(webdriver.By.id('ABC')); - element = driver.findElement({id: 'ABC'}); element = driver.findElement(webdriver.By.js('function(){}')); - element = driver.findElement({js: 'function(){}'}); // findElements driver.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); - driver.findElements({ className: 'ABC' }).then(function (elements: webdriver.WebElement[]) { }); driver.findElements(webdriver.By.js('function(){}')).then(function (elements: webdriver.WebElement[]) { }); - driver.findElements({ js: 'function(){}' }).then(function (elements: webdriver.WebElement[]) { }); voidPromise = driver.get('http://www.google.com'); driver.getAllWindowHandles().then(function (handles: string[]) { }); @@ -766,13 +738,11 @@ function TestWebDriver() { stringPromise = driver.getWindowHandle(); booleanPromise = driver.isElementPresent(webdriver.By.className('ABC')); - booleanPromise = driver.isElementPresent({className: 'ABC'}); booleanPromise = driver.isElementPresent(webdriver.By.js('function(){}')); - booleanPromise = driver.isElementPresent({js: 'function(){}'}); - var options: webdriver.WebDriverOptions = driver.manage(); - var navigation: webdriver.WebDriverNavigation = driver.navigate(); - var locator: webdriver.WebDriverTargetLocator = driver.switchTo(); + var options: webdriver.Options = driver.manage(); + var navigation: webdriver.Navigation = driver.navigate(); + var locator: webdriver.TargetLocator = driver.switchTo(); var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); driver.setFileDetector(fileDetector); @@ -795,7 +765,7 @@ function TestWebDriver() { function TestSerializable() { var serializable: webdriver.Serializable; - var serial: string|webdriver.promise.Promise = serializable.serialize(); + var serial: string|webdriver.promise.IThenable = serializable.serialize(); } function TestWebElement() { @@ -803,10 +773,10 @@ function TestWebElement() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var promise: webdriver.promise.Promise; + var promise: webdriver.promise.Promise; var element: webdriver.WebElement; - element = new webdriver.WebElement(driver, { ELEMENT: 'ID' }); + element = new webdriver.WebElement(driver, 'elementId'); element = new webdriver.WebElement(driver, promise); var voidPromise: webdriver.promise.Promise; @@ -817,13 +787,8 @@ function TestWebElement() { voidPromise = element.click(); element = element.findElement(webdriver.By.id('ABC')); - element = element.findElement({id: 'ABC'}); - element.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); - element.findElements({ className: 'ABC' }).then(function (elements: webdriver.WebElement[]) { }); - booleanPromise = element.isElementPresent(webdriver.By.className('ABC')); - booleanPromise = element.isElementPresent({className: 'ABC'}); stringPromise = element.getAttribute('class'); stringPromise = element.getCssValue('display'); @@ -840,14 +805,11 @@ function TestWebElement() { voidPromise = element.sendKeys('A', 'B', 'C'); voidPromise = element.sendKeys(stringPromise, stringPromise, stringPromise); voidPromise = element.submit(); - element.getId().then(function (id: typeof webdriver.WebElement.Id) { }); + element.getId().then(function (id: string) { }); element.getRawId().then(function (id: string) { }); - element.serialize().then(function (id: typeof webdriver.WebElement.Id) { }); + element.serialize().then(function (id: webdriver.IWebElementId) { }); - booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, { ELEMENT: 'ID2' })); - - var id: typeof webdriver.WebElement.Id = webdriver.WebElement.Id; - var key: string = webdriver.WebElement.ELEMENT_KEY; + booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, 'elementId')); } function TestWebElementPromise() { @@ -877,7 +839,7 @@ function TestLogging() { preferences.setLevel(webdriver.logging.Type.BROWSER, webdriver.logging.Level.ALL); var prefs: any = preferences.toJSON(); - var level: webdriver.logging.ILevel = webdriver.logging.getLevel('OFF'); + var level: webdriver.logging.Level = webdriver.logging.getLevel('OFF'); level = webdriver.logging.getLevel(1); level = webdriver.logging.Level.ALL; @@ -887,10 +849,10 @@ function TestLogging() { level = webdriver.logging.Level.SEVERE; level = webdriver.logging.Level.WARNING; - var name: string = level.name; - var value: number = level.value; + var name: string = level.name(); + var value: number = level.value(); - var type: string; + var type: webdriver.logging.Type; type = webdriver.logging.Type.BROWSER; type = webdriver.logging.Type.CLIENT; type = webdriver.logging.Type.DRIVER; @@ -913,9 +875,6 @@ function TestLoggingEntry() { var message: string = entry.message; var timestamp: number = entry.timestamp; var type: string = entry.type; - - entry = webdriver.logging.Entry.fromClosureLogRecord({}); - entry = webdriver.logging.Entry.fromClosureLogRecord({}, webdriver.logging.Type.DRIVER); } function TestPromiseModule() { @@ -946,29 +905,29 @@ function TestPromiseModule() { return 5; }, this, 1, 2, 3).then(function (value: number) { }); - var numbersPromise: webdriver.promise.Promise = webdriver.promise.filter([1, 2, 3], function (el: number, index: number, arr: number[]) { + var numbersPromise: webdriver.promise.Promise = webdriver.promise.filter([1, 2, 3], function (element: number, type: any, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.filter([1, 2, 3], function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter([1, 2, 3], function (element: number, type: any, index: number, arr: number[]) { return true; }, this); - numbersPromise = webdriver.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { return true; }, this); - numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, type: any, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, type: any, index: number, arr: number[]) { return true; }, this); - numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { return true; }, this); @@ -995,26 +954,13 @@ function TestPromiseModule() { var bool: boolean = webdriver.promise.isGenerator(function () { }); var isPromise: boolean = webdriver.promise.isPromise('ABC'); - voidPromise = webdriver.promise.rejected({a: 123}); + stringPromise = webdriver.promise.rejected('{a: 123}'); webdriver.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); numberPromise = webdriver.promise.when('abc', function(value: any) { return 123; }, function(err: Error) { return 123; }); } -function TestStacktraceModule() { - var bool: boolean = webdriver.stacktrace.BROWSER_SUPPORTED; - - var frame: webdriver.stacktrace.Frame = new webdriver.stacktrace.Frame(); - var baseFrame: webdriver.stacktrace.Frame = frame; - - var snapshot: webdriver.stacktrace.Snapshot = new webdriver.stacktrace.Snapshot(); - var baseSnapshot: webdriver.stacktrace.Snapshot = snapshot; - - var err: Error = webdriver.stacktrace.format(new Error("Error")); - var frames: webdriver.stacktrace.Frame[] = webdriver.stacktrace.get(); -} - function TestUntilModule() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). @@ -1125,13 +1071,12 @@ function TestPromiseClass() { } function TestThenableClass() { - var thenable: webdriver.promise.Thenable = new webdriver.promise.Thenable(); + var thenable: webdriver.promise.Promise = new webdriver.promise.Promise(); thenable.cancel('Abort'); var isPending: boolean = thenable.isPending(); - thenable = thenable.then(); thenable = thenable.then(function (a: string) { return 'cde'; }); thenable = thenable.then(function (a: string) { return 'cde'; }, function (e: any) { }); thenable = thenable.then(function (a: string) { return 'cde'; }, function (e: any) { return 123; }); @@ -1144,76 +1089,30 @@ function TestThenableClass() { function TestErrorCode() { var errorCode: number; - errorCode = webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE; - errorCode = webdriver.error.ErrorCode.ELEMENT_NOT_VISIBLE; - errorCode = webdriver.error.ErrorCode.IME_ENGINE_ACTIVATION_FAILED; - errorCode = webdriver.error.ErrorCode.IME_NOT_AVAILABLE; - errorCode = webdriver.error.ErrorCode.INVALID_COOKIE_DOMAIN; - errorCode = webdriver.error.ErrorCode.INVALID_ELEMENT_COORDINATES; - errorCode = webdriver.error.ErrorCode.INVALID_ELEMENT_STATE; - errorCode = webdriver.error.ErrorCode.INVALID_SELECTOR_ERROR; - errorCode = webdriver.error.ErrorCode.INVALID_XPATH_SELECTOR; - errorCode = webdriver.error.ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPE; - errorCode = webdriver.error.ErrorCode.JAVASCRIPT_ERROR; - errorCode = webdriver.error.ErrorCode.METHOD_NOT_ALLOWED; - errorCode = webdriver.error.ErrorCode.MODAL_DIALOG_OPENED; - errorCode = webdriver.error.ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS; - errorCode = webdriver.error.ErrorCode.NO_MODAL_DIALOG_OPEN; - errorCode = webdriver.error.ErrorCode.NO_SUCH_ELEMENT; - errorCode = webdriver.error.ErrorCode.NO_SUCH_FRAME; - errorCode = webdriver.error.ErrorCode.NO_SUCH_WINDOW; - errorCode = webdriver.error.ErrorCode.SCRIPT_TIMEOUT; - errorCode = webdriver.error.ErrorCode.SESSION_NOT_CREATED; - errorCode = webdriver.error.ErrorCode.SQL_DATABASE_ERROR; - errorCode = webdriver.error.ErrorCode.STALE_ELEMENT_REFERENCE; - errorCode = webdriver.error.ErrorCode.SUCCESS; - errorCode = webdriver.error.ErrorCode.TIMEOUT; - errorCode = webdriver.error.ErrorCode.UNABLE_TO_SET_COOKIE; - errorCode = webdriver.error.ErrorCode.UNKNOWN_COMMAND; - errorCode = webdriver.error.ErrorCode.UNKNOWN_ERROR; - errorCode = webdriver.error.ErrorCode.UNSUPPORTED_OPERATION; - errorCode = webdriver.error.ErrorCode.XPATH_LOOKUP_ERROR; -} - -function TestError() { - var error: webdriver.error.Error; - - error = new webdriver.error.Error(webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE); - error = new webdriver.error.Error(webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE, 'Message'); - - var code: number = error.code; - var state: string = error.state; - var message: string = error.message; - var name: string = error.name; - var stack: string = error.stack; - var isAutomationError: boolean = error.isAutomationError; - var errorStr: string = error.toString(); - - state = webdriver.error.Error.State.ELEMENT_NOT_SELECTABLE - state = webdriver.error.Error.State.ELEMENT_NOT_VISIBLE; - state = webdriver.error.Error.State.IME_ENGINE_ACTIVATION_FAILED; - state = webdriver.error.Error.State.IME_NOT_AVAILABLE; - state = webdriver.error.Error.State.INVALID_COOKIE_DOMAIN; - state = webdriver.error.Error.State.INVALID_ELEMENT_COORDINATES; - state = webdriver.error.Error.State.INVALID_ELEMENT_STATE; - state = webdriver.error.Error.State.INVALID_SELECTOR; - state = webdriver.error.Error.State.JAVASCRIPT_ERROR; - state = webdriver.error.Error.State.MOVE_TARGET_OUT_OF_BOUNDS; - state = webdriver.error.Error.State.NO_SUCH_ALERT; - state = webdriver.error.Error.State.NO_SUCH_DOM - state = webdriver.error.Error.State.NO_SUCH_ELEMENT; - state = webdriver.error.Error.State.NO_SUCH_FRAME; - state = webdriver.error.Error.State.NO_SUCH_WINDOW; - state = webdriver.error.Error.State.SCRIPT_TIMEOUT; - state = webdriver.error.Error.State.SESSION_NOT_CREATED; - state = webdriver.error.Error.State.STALE_ELEMENT_REFERENCE; - state = webdriver.error.Error.State.SUCCESS; - state = webdriver.error.Error.State.TIMEOUT; - state = webdriver.error.Error.State.UNABLE_TO_SET_COOKIE; - state = webdriver.error.Error.State.UNEXPECTED_ALERT_OPEN - state = webdriver.error.Error.State.UNKNOWN_COMMAND; - state = webdriver.error.Error.State.UNKNOWN_ERROR; - state = webdriver.error.Error.State.UNSUPPORTED_OPERATION; + errorCode = new webdriver.error.ElementNotSelectableError().code(); + errorCode = new webdriver.error.ElementNotVisibleError().code(); + errorCode = new webdriver.error.InvalidArgumentError().code(); + errorCode = new webdriver.error.InvalidCookieDomainError().code(); + errorCode = new webdriver.error.InvalidElementCoordinatesError().code(); + errorCode = new webdriver.error.InvalidElementStateError().code(); + errorCode = new webdriver.error.InvalidSelectorError().code(); + errorCode = new webdriver.error.NoSuchSessionError().code(); + errorCode = new webdriver.error.JavascriptError().code(); + errorCode = new webdriver.error.MoveTargetOutOfBoundsError().code(); + errorCode = new webdriver.error.NoSuchAlertError().code(); + errorCode = new webdriver.error.NoSuchElementError().code(); + errorCode = new webdriver.error.NoSuchFrameError().code(); + errorCode = new webdriver.error.NoSuchWindowError().code(); + errorCode = new webdriver.error.ScriptTimeoutError().code(); + errorCode = new webdriver.error.SessionNotCreatedError().code(); + errorCode = new webdriver.error.StaleElementReferenceError().code(); + errorCode = new webdriver.error.TimeoutError().code(); + errorCode = new webdriver.error.UnableToSetCookieError().code(); + errorCode = new webdriver.error.UnableToCaptureScreenError().code(); + errorCode = new webdriver.error.UnexpectedAlertOpenError().code(); + errorCode = new webdriver.error.UnknownCommandError().code(); + errorCode = new webdriver.error.UnknownMethodError().code(); + errorCode = new webdriver.error.UnsupportedOperationError().code(); } function TestTestingModule() {