diff --git a/angular-protractor/angular-protractor-tests.ts b/angular-protractor/angular-protractor-tests.ts index 5ca9ecde46..b8b9585f47 100644 --- a/angular-protractor/angular-protractor-tests.ts +++ b/angular-protractor/angular-protractor-tests.ts @@ -1,11 +1,7 @@ /// function TestWebDriverExports() { - var abstractBuilder: protractor.AbstractBuilder = new protractor.AbstractBuilder(); - var baseAbstractBuilder: webdriver.AbstractBuilder = abstractBuilder; - - var button: protractor.Button = new protractor.Button(); - var baseButton: webdriver.Button = button; + var button: number = protractor.Button.LEFT; var key: string = protractor.Key.ADD; var chord: string = protractor.Key.chord(protractor.Key.NUMPAD0, protractor.Key.NUMPAD1); @@ -18,12 +14,6 @@ function TestWebDriverExports() { var action: protractor.ActionSequence = new protractor.ActionSequence(driver); var baseAction: webdriver.ActionSequence = action; - var alert: protractor.Alert = new protractor.Alert(driver, 'Message'); - var baseAlert: webdriver.Alert = alert; - - var unhandledAlertError: protractor.UnhandledAlertError = new protractor.UnhandledAlertError('Message', alert); - var baseUnhandledAlertError: webdriver.UnhandledAlertError = unhandledAlertError; - var browser: string = protractor.Browser.ANDROID; var builder: protractor.Builder = new protractor.Builder(); @@ -42,89 +32,168 @@ function TestWebDriverExports() { var eventEmitter: protractor.EventEmitter = new protractor.EventEmitter(); var baseEventEmitter: webdriver.EventEmitter = eventEmitter; - var firefoxDomExecutor: protractor.FirefoxDomExecutor = new protractor.FirefoxDomExecutor(); - var baseFirefoxDomExecutor: webdriver.FirefoxDomExecutor = firefoxDomExecutor; - var webElement: protractor.WebElement = new protractor.WebElement(driver, new protractor.promise.Promise()); var baseWebElement: webdriver.WebElement = webElement; - var locator: protractor.Locator = new protractor.Locator('id', 'ABC'); - var baseLocator: webdriver.Locator = locator; + 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'); - // logging module + var driver: protractor.WebDriver = new protractor.WebDriver(session, {}); + driver = new protractor.WebDriver(session, {}, new webdriver.promise.ControlFlow()); + var baseDriver: webdriver.WebDriver = driver; - var levelName: string = protractor.logging.LevelName.ALL; + 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.Level = protractor.logging.Level.ALL; + 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'); - protractor.logging.Preferences = { a: 123 }; + var prefs: protractor.logging.Preferences = new protractor.logging.Preferences(); +} - // promise module +function TestWebDriverPromiseModule() { + var cancelError: protractor.promise.CancellationError = new protractor.promise.CancellationError(); + cancelError = new protractor.promise.CancellationError('message'); + var baseCancelError: webdriver.promise.CancellationError = cancelError; - var promise: protractor.promise.Promise = new protractor.promise.Promise(); - var basePromise: webdriver.promise.Promise = promise; + var thenable: protractor.promise.Thenable = new protractor.promise.Thenable(); + var baseThenable: webdriver.promise.Thenable = thenable; - var deferred: protractor.promise.Deferred = new protractor.promise.Deferred(); - var baseDeferred: webdriver.promise.Deferred = deferred; + 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; - protractor.promise.asap(promise, function(value: any){ return true; }); - protractor.promise.asap(promise, function(value: any){}, function(err: any) { return 'ABC'; }); + var arrayPromise: protractor.promise.Promise = protractor.promise.all([new protractor.promise.Promise(), new protractor.promise.Promise()]); - promise = protractor.promise.checkedNodeCall(function(err: any, value: any) { return 123; }); + 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) { }); + promise = protractor.promise.createFlow(function (newFlow: webdriver.promise.ControlFlow) { }); - deferred = protractor.promise.defer(function() {}); - deferred = protractor.promise.defer(function(reason?: any) {}); + 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.fulfilled({ a: 123 }); - promise = protractor.promise.fullyResolved({a: 123}); + promise = protractor.promise.fullyResolved({ a: 123 }); - var isPromise: boolean = protractor.promise.isPromise('ABC'); + var bool: boolean = protractor.promise.isGenerator(function () { }); + var bool: boolean = protractor.promise.isPromise('ABC'); - promise = protractor.promise.rejected({a: 123}); + 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; }); + promise = protractor.promise.when(promise, function (value: any) { return 123; }, function (err: Error) { return 123; }); +} - // error module +function TestWebDriverStacktraceModule() { + var bool: boolean = protractor.stacktrace.BROWSER_SUPPORTED; - 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; + var frame: protractor.stacktrace.Frame = new protractor.stacktrace.Frame(); + var baseFrame: webdriver.stacktrace.Frame = frame; - // process module + var snapshot: protractor.stacktrace.Snapshot = new protractor.stacktrace.Snapshot(); + var baseSnapshot: webdriver.stacktrace.Snapshot = snapshot; - var isNative: boolean = protractor.process.isNative(); - var value: string; + var err: Error = protractor.stacktrace.format(new Error("Error")); + var frames: protractor.stacktrace.Frame[] = protractor.stacktrace.get(); +} - value = protractor.process.getEnv('name'); - value = protractor.process.getEnv('name', 'default'); +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; - protractor.process.setEnv('name', 'value'); - protractor.process.setEnv('name', 123); + 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 TestProtractor() { @@ -133,31 +202,47 @@ function TestProtractor() { withCapabilities(webdriver.Capabilities.chrome()). build(); - ptor = new protractor.Protractor(driver); - ptor = new protractor.Protractor(driver, 'baseUrl'); - ptor = new protractor.Protractor(driver, 'baseUrl', 'rootElement'); - ptor = protractor.getInstance(); - protractor.setInstance(ptor); - 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')); - var promise: webdriver.promise.Promise; - promise = ptor.findElements(by.css('.class')); - promise = ptor.isElementPresent(by.css('.class')); - promise = ptor.isElementPresent(webElement); + 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'); @@ -173,16 +258,43 @@ function TestProtractor() { elementArrayFinder = ptor.$$('.class'); - var locationAbsUrl: webdriver.promise.Promise = ptor.getLocationAbsUrl(); + var locationAbsUrl: webdriver.promise.Promise = ptor.getLocationAbsUrl(); ptor.setLocation('webaddress.com'); - promise = ptor.get('webaddress.com'); - promise = ptor.get('webdaddress.com', 45); + 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() { @@ -192,80 +304,121 @@ function TestElement() { function TestElementFinder() { var elementFinder: protractor.ElementFinder = element(by.id('id')); - var promise: webdriver.promise.Promise; + var voidPromise: webdriver.promise.Promise; + var stringPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; - promise = elementFinder.click(); - promise = elementFinder.allowAnimations('string'); - promise = elementFinder.sendKeys(protractor.Key.UP, protractor.Key.DOWN); - promise = elementFinder.getTagName(); - promise = elementFinder.getCssValue('display'); - promise = elementFinder.getAttribute('atribute'); - promise = elementFinder.getText(); - promise = elementFinder.getSize(); - promise = elementFinder.getLocation(); - promise = elementFinder.isEnabled(); - promise = elementFinder.isSelected(); - promise = elementFinder.submit(); - promise = elementFinder.clear(); - promise = elementFinder.isDisplayed(); - promise = elementFinder.getOuterHtml(); - promise = elementFinder.getInnerHtml(); - promise = elementFinder.isElementPresent(by.id('id')); - promise = elementFinder.$('.class'); - promise = elementFinder.$$('.class'); - promise = elementFinder.evaluate('expression'); - promise = elementFinder.isPresent(); + 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; + 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 promise: webdriver.promise.Promise; - var elementFinder: protractor.ElementFinder; + + 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 findersArray: protractor.ElementFinder[] = elementArrayFinder.asElementFinders_(); var driverElementArray: webdriver.WebElement[] = elementArrayFinder.getWebElements(); - elementFinder = elementArrayFinder.get(42); + var elementFinder: protractor.ElementFinder = elementArrayFinder.get(42); elementFinder = elementArrayFinder.first(); elementFinder = elementArrayFinder.last(); - promise = elementArrayFinder.count(); - promise = elementArrayFinder.asElementFinders_(); + elementFinder = elementArrayFinder.toElementFinder_() + var numberPromise: protractor.promise.Promise = elementArrayFinder.count(); elementArrayFinder.each(function(element: protractor.ElementFinder){ // nothing }); - elementArrayFinder.map(function(element: protractor.ElementFinder, index: number){ - // nothing - }); - elementArrayFinder.filter(function(element: protractor.ElementFinder, index: number){ + stringPromise = elementArrayFinder.map(function(element: protractor.ElementFinder, index: number){ + return 'abc'; + }) + 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){ + 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 angular specific locator strategies. +// This function tests the locator strategies. function TestLocatorStrategies() { - var ptor: protractor.Protractor = protractor.getInstance(); + var ptor: protractor.Protractor = browser; var webElement: webdriver.WebElement; - // Protractor Specific Locators 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')); @@ -277,4 +430,23 @@ function TestLocatorStrategies() { 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/angular-protractor/angular-protractor.d.ts b/angular-protractor/angular-protractor.d.ts index 2de49a0a45..8e24c5f572 100644 --- a/angular-protractor/angular-protractor.d.ts +++ b/angular-protractor/angular-protractor.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular Protractor 1.0.0-rc4 +// Type definitions for Angular Protractor 1.5.0 // Project: https://github.com/angular/protractor // Definitions by: Bill Armstrong // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -8,55 +8,72 @@ declare module protractor { //region Wrapped webdriver Items - class AbstractBuilder extends webdriver.AbstractBuilder {} class ActionSequence extends webdriver.ActionSequence {} - class Alert extends webdriver.Alert {} class Builder extends webdriver.Builder {} - class Button extends webdriver.Button {} class Capabilities extends webdriver.Capabilities {} class Command extends webdriver.Command {} class EventEmitter extends webdriver.EventEmitter {} - class FirefoxDomExecutor extends webdriver.FirefoxDomExecutor {} - class Locator extends webdriver.Locator {} class Session extends webdriver.Session {} class WebDriver extends webdriver.WebDriver {} - class Browser extends webdriver.Browser {} - class Capability extends webdriver.Capability {} - class CommandName extends webdriver.CommandName {} - class Key extends webdriver.Key {} - class UnhandledAlertError extends webdriver.UnhandledAlertError {} class WebElement extends webdriver.WebElement {} + class WebElementPromise extends webdriver.WebElementPromise { } - module command { - class Command extends webdriver.Command {} - class CommandName extends webdriver.CommandName {} - } + var Browser: webdriver.IBrowser; + var Button: webdriver.IButton; + var Capability: webdriver.ICapability; + var CommandName: webdriver.ICommandName; + var Key: webdriver.IKey; module error { class Error extends webdriver.error.Error {} - class ErrorCode extends webdriver.error.ErrorCode {} - } - - module events { - class EventEmitter extends webdriver.EventEmitter {} + var ErrorCode: webdriver.error.IErrorCode; } module logging { - var Preferences: any; + class Preferences extends webdriver.logging.Preferences { } + class Entry extends webdriver.logging.Entry { } - class LevelName extends webdriver.logging.LevelName {} - class Type extends webdriver.logging.Type {} - class Level extends webdriver.logging.Level {} - class Entry extends webdriver.logging.Entry {} + var Type: webdriver.logging.IType; + var Level: webdriver.logging.ILevelValues; - function getLevel(nameOrValue: string): webdriver.logging.Level; - function getLevel(nameOrValue: number): webdriver.logging.Level; + function getLevel(nameOrValue: string): webdriver.logging.ILevel; + function getLevel(nameOrValue: number): webdriver.logging.ILevel; } module promise { - class Promise extends webdriver.promise.Promise {} - class Deferred extends webdriver.promise.Deferred {} - class ControlFlow extends webdriver.promise.ControlFlow {} + 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. @@ -72,7 +89,7 @@ declare module protractor { * @return {!webdriver.promise.Promise} A promise that resolves to the callback * result. */ - function createFlow(callback: (flow: webdriver.promise.ControlFlow) => any): webdriver.promise.Promise; + function createFlow(callback: (flow: webdriver.promise.ControlFlow) => R): webdriver.promise.Promise; /** * Determines whether a {@code value} should be treated as a promise. @@ -83,28 +100,83 @@ declare module protractor { */ 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; + 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. - * @param {Function=} opt_canceller Function to call when cancelling the - * computation of this instance's value. * @return {!webdriver.promise.Deferred} The new deferred object. */ - function defer(opt_canceller?: any): webdriver.promise.Deferred; + 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?: any): webdriver.promise.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. @@ -112,7 +184,7 @@ declare module protractor { * usually an Error or a string. * @return {!webdriver.promise.Promise} The rejected promise. */ - function rejected(opt_reason?: any): webdriver.promise.Promise; + function rejected(opt_reason?: any): webdriver.promise.Promise; /** * Wraps a function that is assumed to be a node-style callback as its final @@ -124,7 +196,49 @@ declare module protractor { * @return {!webdriver.promise.Promise} A promise that will be resolved with the * result of the provided function's callback. */ - function checkedNodeCall(fn: (error: any, value: any) => any): webdriver.promise.Promise; + 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 @@ -137,19 +251,8 @@ declare module protractor { * rejected. * @return {!webdriver.promise.Promise} A new promise. */ - function when(value: any, opt_callback?: (value: any) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise; - - /** - * Invokes the appropriate callback function as soon as a promised - * {@code value} is resolved. This function is similar to - * {@code 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: (value: any) => any, opt_errback?: (error: any) => any): void; + 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 @@ -170,7 +273,7 @@ declare module protractor { * @return {!webdriver.promise.Promise} A promise for a fully resolved version * of the input value. */ - function fullyResolved(value: any): webdriver.promise.Promise; + function fullyResolved(value: any): webdriver.promise.Promise; /** * Changes the default flow to use when no others are active. @@ -178,55 +281,246 @@ declare module protractor { * @throws {Error} If the default flow is not currently active. */ function setDefaultFlow(flow: webdriver.promise.ControlFlow): void; - } - module process { + module stacktrace { + class Frame extends webdriver.stacktrace.Frame { } + class Snapshot extends webdriver.stacktrace.Snapshot { } /** - * Queries for a named environment variable. - * @param {string} name The name of the environment variable to look up. - * @param {string=} opt_default The default value if the named variable is not - * defined. - * @return {string} The queried environment variable. + * 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 getEnv(name: string, opt_default?: string): string; + function format(error: any): any; /** - * @return {boolean} Whether the current process is Node's native process - * object. + * 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 isNative(): boolean; + function get(): webdriver.stacktrace.Frame[]; /** - * Sets an environment value. If the new value is either null or undefined, the - * environment variable will be cleared. - * @param {string} name The value to set. - * @param {*} value The new value; will be coerced to a string. + * Whether the current browser supports stack traces. + * + * @type {boolean} + * @const */ - function setEnv(name: string, value: any): void; + var BROWSER_SUPPORTED: boolean; + } + module 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; } //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} - */ + + /** + * 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; @@ -240,115 +534,605 @@ declare module protractor { all(locator: webdriver.Locator): ElementArrayFinder; } - interface ElementFinder { + interface ElementFinder extends webdriver.IWebElement, webdriver.promise.IThenable { /** - * Use as: element(locator).element(locator) - * Calls to element may be chained to find elements within a parent. - * - * @param {webdriver.Locator} locator The locator that will be used to find descendents. - * - * @return {protractor.ElementFinder} The descendent element found by the locator - */ - element(locator: webdriver.Locator): protractor.ElementFinder; + * 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; /** - * Use as: element(locator).all(locator) - * Calls to element may be chained to find an array of elements within a parent. - * - * @param {webdriver.Locator} locator The locator that will be used to find descendents. - * - * @return {protractor.ElementArrayFinder} The descendent elements found by the locator - */ - all(locator: webdriver.Locator): protractor.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. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElement - * @return {!protractor.WebElement} - */ - $(selector: string): protractor.WebElement; + * 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; /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElements - * @return {!webdriver.promise.Promise} A promise that will be resolved to an - * array of the located {@link webdriver.WebElement}s. - */ - $$(selector: string): webdriver.promise.Promise; + * 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; /** - * Use as: element(locator).isPresent() - * Determine whether the element is present on the page. - * - * @return {protractor.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; /** - * Override for WebElement.prototype.isElementPresent so that protractor waits - * for Angular to settle before making the check. - * - * @see ElementFinder.isPresent - * @return {!webdriver.promise.Promise} which resolves to whether the element is present on the page. - */ - isElementPresent(locator: webdriver.Locator): webdriver.promise.Promise; - - /** - * Return this ElementFinder's locator. - * - * @return {webdriver.Locator} - */ + * @see ElementArrayFinder.prototype.locator + * + * @return {webdriver.Locator} + */ locator(): webdriver.Locator; /** - * Use as: element(locator).getWebElement() - * Returns the WebElement represented by this ElementFinder. - * Throws the WebDriver error if the element doesn't exist. - * If index is null, it makes sure that there is only one underlying WebElement - * described by the chain of locators and issues a warning otherwise. - * If index is not null, it retrieves the WebElement specified by the index.. - * @return {webdriver.WebElement} The WebElement represented by the ElementFinder. - */ + * 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; /** - * Evalates the input as if it were on the scope of the current element. + * 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; + + /** + * 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. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param {?(function(T): (R|webdriver.promise.Promise.))=} 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 {?(function(*): (R|webdriver.promise.Promise.))=} opt_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 + */ + then(opt_callback?: (value: ElementFinder) => any, opt_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().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 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): webdriver.promise.Promise; + + /** + * 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; + + /** + * 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[]) => 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_(): ElementFinder[]; + + /** + * 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 {!webdriver.promise.Promise} A promise that will resolve to the - * evaluated expression. The result will be resolved as in + * @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): webdriver.promise.Promise; + evaluate(expression: string): ElementArrayFinder; /** - * Determine if animation is allowed on the current element. + * Determine if animation is allowed on the current underlying elements. * @param {string} value * - * @return {ElementFinder} which resolves to whether animation is allowed. - */ - allowAnimations(value: string): webdriver.promise.Promise; - - /** - * Access the underlying actionResult of ElementFinder. Implementation allows ElementFinder to be used as a webdriver.promise.Promise. - * @param {function(webdriver.promise.Promise)} fn Function which takes the value of the underlying actionResult. + * @example + * // Turns off ng-animate animations for all elements in the + * element(by.css('body')).allowAnimations(false); * - * @return {webdriver.promise.Promise} Promise which contains the results of evaluating fn. + * @return {ElementArrayFinder} which resolves to whether animation is allowed. */ - then(fn: IThenFunction): webdriver.promise.Promise; + 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; + click(): webdriver.promise.Promise; /** * Schedules a command to type a sequence on the DOM element represented by this @@ -390,14 +1174,14 @@ declare module protractor { * @return {!webdriver.promise.Promise} A promise that will be resolved when all * keys have been typed. */ - sendKeys(...var_args: string[]): webdriver.promise.Promise; + 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; + getTagName(): webdriver.promise.Promise; /** * Schedules a command to query for the computed style of the element @@ -414,7 +1198,7 @@ declare module protractor { * @return {!webdriver.promise.Promise} A promise that will be resolved with the * requested CSS value. */ - getCssValue(cssStyleProperty: string): webdriver.promise.Promise; + getCssValue(cssStyleProperty: string): webdriver.promise.Promise; /** * Schedules a command to query for the value of the given attribute of the @@ -443,7 +1227,7 @@ declare module protractor { * @return {!webdriver.promise.Promise} A promise that will be resolved with the * attribute's value. */ - getAttribute(attributeName: string): webdriver.promise.Promise; + getAttribute(attributeName: string): webdriver.promise.Promise; /** * Get the visible (i.e. not hidden by CSS) innerText of this element, including @@ -451,7 +1235,7 @@ declare module protractor { * @return {!webdriver.promise.Promise} A promise that will be resolved with the * element's visible text. */ - getText(): webdriver.promise.Promise; + getText(): webdriver.promise.Promise; /** * Schedules a command to compute the size of this element's bounding box, in @@ -459,14 +1243,14 @@ declare module protractor { * @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; + 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; + getLocation(): webdriver.promise.Promise; /** * Schedules a command to query whether the DOM element represented by this @@ -474,14 +1258,14 @@ declare module protractor { * @return {!webdriver.promise.Promise} A promise that will be resolved with * whether this element is currently enabled. */ - isEnabled(): webdriver.promise.Promise; + 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; + isSelected(): webdriver.promise.Promise; /** * Schedules a command to submit the form containing this element (or this @@ -490,7 +1274,7 @@ declare module protractor { * @return {!webdriver.promise.Promise} A promise that will be resolved when * the form has been submitted. */ - submit(): webdriver.promise.Promise; + submit(): webdriver.promise.Promise; /** * Schedules a command to clear the {@code value} of this element. This command @@ -499,276 +1283,173 @@ declare module protractor { * @return {!webdriver.promise.Promise} A promise that will be resolved when * the element has been cleared. */ - clear(): webdriver.promise.Promise; + 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; + 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; + 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; - - /** - * @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 - */ - toWireValue(): webdriver.promise.Promise; + getInnerHtml(): webdriver.promise.Promise; } - interface IThenFunction { - (promiseResult: any): any; - } - - - interface ElementArrayFinder { - /** - * Use as: element.all(locator).getWebElements() - * Returns the array of WebElements represented by this ElementArrayFinder. - * - * @return {Array.} Array of WebElements represented by this ElementArrayFinder - */ - getWebElements(): webdriver.WebElement[]; - - /** - * Use as: element.all(locator).get(index) - * Get an element found by the locator by index. The index starts at 0. This does not actually retrieve the underlying element. - * - * @param {number} index Element index. - * - * @return {protractor.ElementFinder} Finder representing element at the given index - */ - get(index: number): protractor.ElementFinder; - - - /** - * Use as: element.all(locator).first() - * Get the first matching element for the locator. This does not actually retrieve the underlying element. - * - * @return {Protractor.ElementFinder} Finder representing the first matching element - */ - first(): protractor.ElementFinder; - - /** - * Use as: element.all(locator).last() - * Get the last matching element for the locator. This does not actually retrieve the underlying element. - * - * @return {Protractor.ElementFinder} Finder representing the last matching element - */ - last(): protractor.ElementFinder; - - /** - * Use as: element.all(locator).getWebElements() - * Returns the array of WebElements represented by this ElementArrayFinder. - * - * @return {!webdriver.promise.Promise} The array of WebElements represented by this ElementArrayFinder - */ - count(): webdriver.promise.Promise; - - /** - * Use as: element.all(locator).each(eachFunction) - * Calls the input function on each ElementFinder found by the locator. - * - * @param {function(ElementFinder)} fn Input function. - */ - each(fn: IEachFunction): void; - - /** - * Use as: element.all(locator).map(mapFunction) - * Apply a map function to each element found using the locator. The callback receives the ElementFinder as the first argument and the index as a second arg. - * - * @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: IMapFunction): webdriver.promise.Promise; - - /** - * Use as: element.all(locator).filter(filterFn) - * Apply a filter function to each element found using the locator. Returns promise of a new array 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. - * - * @param {function(ElementFinder, number): webdriver.promise.Promise} filterFn Filter function that will test if an element should be returned. filterFn should return a promise that resolves to a boolean. - * - * @return {!webdriver.promise.Promise} A promise that resolves to an array of ElementFinders that satisfy the filter function. - */ - filter(func: IFilterFunction): webdriver.promise.Promise; - - /** - * Use as: element.all(locator).reduce(reduceFn) - * 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. - * - * @param {function(number, ElementFinder, number, Array.): webdriver.promise.Promise} 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(func: IReductionFunction, initialValue: any): webdriver.promise.Promise; - - /** - * Represents the ElementArrayFinder as an array of ElementFinders. - * - * @return {!webdriver.promise.Promise} Return a promise, which resolves to a list (array) - * of ElementFinders specified by the locator. - */ - asElementFinders_(): webdriver.promise.Promise; - - - /** - * Find the elements specified by the locator. The input function is passed - * to the resulting promise, which resolves to an array of ElementFinders. - * - * Use as: element.all(locator).then(thenFunction) - *
    - *
  • First
  • - *
  • Second
  • - *
  • Third
  • - *
- * - * element.all(by.css('.items li')).then(function(arr) { - * expect(arr.length).toEqual(3); - * }); - * - * @param {function(Array.)} fn - * - * @type {webdriver.promise.Promise} a promise which will resolve to - * an array of ElementFinders matching the locator. - */ - then(fn: IElementArrayFinderThenFunction): webdriver.promise.Promise; - } - - interface IEachFunction { - (element: protractor.ElementFinder): void; - } - - interface IMapFunction { - (element: ElementFinder, index: number): any; - } - - interface IFilterFunction { - (element: ElementFinder, index: number): webdriver.promise.Promise; - } - - interface IReductionFunction { - (accumulator: any, element: protractor.ElementFinder, index?: number, array?: protractor.ElementFinder[]): webdriver.promise.Promise; - } - - interface IElementArrayFinderThenFunction { - (promiseResult: ElementFinder[]): any; - } - - class LocatorWithColumn extends webdriver.Locator { + interface LocatorWithColumn extends webdriver.Locator { column(index: number): webdriver.Locator; } - class RepeaterLocator extends LocatorWithColumn { + interface RepeaterLocator extends LocatorWithColumn { row(index: number): LocatorWithColumn; } interface IProtractorLocatorStrategy extends webdriver.ILocatorStrategy { /** * Add a locator to this instance of ProtractorBy. This locator can then be - * used with element(by.()). + * used with element(by.locatorName(args)). * - * @param {string} name - * @param {function|string} script A script to be run in the context of + * @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 begins with the element scoping the search, and then - * contains any args passed into the locator. It should return - * an array of elements. + * 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: any): void; + addLocator(name: string, script: string): void; + addLocator(name: string, script: Function): void; /** - * Usage: - * {{status}} - * var status = element(by.binding('{{status}}')); + * 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 {webdriver.Locator} + * @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 {webdriver.Locator} + * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} */ exactBinding(bindingDescriptor: string): webdriver.Locator; /** - * * Find an element by ng-model expression. * - * Usage: - * - * var input = element(by.model('person.name')); - * input.sendKeys('123'); - * expect(input.getAttribute('value')).toBe('Foo123'); + * @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. - * @return {webdriver.Locator} */ model(model: string): webdriver.Locator; /** * Find a button by text. * - * Usage: - * - * element(by.buttonText('Save')); + * @view + * + * + * @example + * element(by.buttonText('Save')); * * @param {string} searchText - * @return {webdriver.Locator} + * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} */ buttonText(searchText: string): webdriver.Locator; - /** * Find a button by partial text. * - * Usage: - * - * element(by.partialButtonText('Save')); + * @view + * + * + * @example + * element(by.partialButtonText('Save')); * * @param {string} searchText - * @return {webdriver.Locator} + * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} */ partialButtonText(searchText: string): webdriver.Locator; + /** * Find elements inside an ng-repeat. * - * Usage: + * @view *
* {{cat.name}} * {{cat.age}} @@ -782,6 +1463,7 @@ declare module protractor { *

{{book.blurb}}

*
* + * @example * // Returns the DIV for the second cat. * var secondCat = element(by.repeater('cat in pets').row(1)); * @@ -829,98 +1511,111 @@ declare module protractor { * @example * // Returns the DIV for the dog, but not cat. * var dog = element(by.cssContainingText('.pet', 'Dog')); - * - * @param cssSelector {string} - * @param searchText {string} - * @return {webdriver.Locator} */ cssContainingText(cssSelector: string, searchText: string): webdriver.Locator; /** * Find an element by ng-options expression. * - * Usage: + * @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. - * @return {webdriver.Locator} */ options(optionsDescriptor: string): webdriver.Locator; } var By: IProtractorLocatorStrategy; - class Protractor extends webdriver.WebDriver { - - //region Constructors + interface Protractor extends webdriver.WebDriver { /** - * @param {webdriver.WebDriver} webdriver - * @param {string=} opt_baseUrl A base URL to run get requests against. - * @param {string=body} opt_rootElement Selector element that has an ng-app in - * scope. - * @constructor - */ - constructor(webdriver: webdriver.WebDriver, opt_baseUrl?: string, opt_rootElement?: string); - - //endregion - - //region Properties - - /** - * The wrapped webdriver instance. Use this to interact with pages that do - * not contain Angular (such as a log-in screen). - * - * @type {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; /** - * All get methods will be resolved against this base URL. Relative URLs are = - * resolved the way anchor tags resolve. - * - * @type {string} - */ + * 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} - */ + * 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} - */ + * 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; /** - * An object that holds custom test parameters. - * - * @type {Object} - */ + * 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; - //endregion - - //region Methods + /** + * The reset URL to use between page loads. + * + * @type {string} + */ + resetUrl: string; /** * Instruct webdriver to wait until Angular has finished rendering and has @@ -929,56 +1624,7 @@ declare module protractor { * @return {!webdriver.promise.Promise} A promise that will resolve to the * scripts return value. */ - waitForAngular(): webdriver.promise.Promise; - - /** - * Waits for Angular to finish rendering before searching for elements. - * @see webdriver.WebDriver.findElement - * - * @param {webdriver.Locator} locator The locator used to find the element. - * @return {!webdriver.WebElement} - */ - findElement(locator: webdriver.Locator): protractor.WebElement; - - /** - * Waits for Angular to finish rendering before searching for elements. - * @see webdriver.WebDriver.findElements - * - * @param {webdriver.Locator} locator The locator used to find the elements. - * @return {!webdriver.promise.Promise} A promise that will be resolved to an - * array of the located {@link webdriver.WebElement}s. - */ - findElements(locator: webdriver.Locator): webdriver.promise.Promise; - - /** - * Tests if an element is present on the page. - * @see webdriver.WebDriver.isElementPresent - * @return {!webdriver.promise.Promise} A promise that will resolve to whether - * the element is present on the page. - */ - isElementPresent(locatorOrElement: webdriver.Locator): webdriver.promise.Promise; - isElementPresent(locatorOrElement: any): webdriver.promise.Promise; - - /** - * Helper function for finding elements. - * - * @type {function(webdriver.Locator): ElementFinder} - */ - element(locator: webdriver.Locator): ElementFinder; - - /** - * Helper function for finding elements by css. - * - * @type {function(string): ElementFinder} - */ - $(cssLocator: string): ElementFinder; - - /** - * Helper function for finding arrays of elements by css. - * - * @type {function(string): ElementArrayFinder} - */ - $$(cssLocator: string): ElementArrayFinder; + waitForAngular(): webdriver.promise.Promise; /** * Add a module to load before Angular whenever Protractor.get is called. @@ -986,13 +1632,18 @@ declare module protractor { * so any module registered here will override preexisting modules with the same * name. * - * @param {string} name The name of the module to load or override. - * @param {string|Function} script The JavaScript to load the module. + * @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: any, ...varArgs: any[]): void; + addMockModule(name: string, script: Function, ...varArgs: any[]): void; /** * Clear the list of registered mock modules. @@ -1001,12 +1652,16 @@ declare module protractor { /** * 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 + * @see webdriver.WebDriver.get * * Navigate to the given destination and loads mock modules before * Angular. Assumes that the page being loaded uses Angular. @@ -1014,9 +1669,10 @@ declare module protractor { * the wrapped webdriver directly. * * @param {string} destination Destination URL. - * @param {number=} opt_timeout Number of seconds to wait for Angular to start. + * @param {number=} opt_timeout Number of milliseconds to wait for Angular to + * start. */ - get(destination: string, opt_timeout?: number): webdriver.promise.Promise; + get(destination: string, opt_timeout?: number): webdriver.promise.Promise; /** * See webdriver.WebDriver.refresh @@ -1028,13 +1684,7 @@ declare module protractor { * * @param {number=} opt_timeout Number of seconds to wait for Angular to start. */ - refresh(opt_timeout?: number): void; - - /** - * Mixin navigation methods back into the navigation object so that - * they are invoked as before, i.e. driver.navigate().refresh() - */ - navigate(): webdriver.WebDriverNavigation; + refresh(opt_timeout?: number): webdriver.promise.Promise; /** * Browse to another page using in-page navigation. @@ -1043,12 +1693,12 @@ declare module protractor { * @returns {!webdriver.promise.Promise} A promise that will resolve once * page has been changed. */ - setLocation(url: string): webdriver.promise.Promise; + setLocation(url: string): webdriver.promise.Promise; /** * Returns the current absolute url from AngularJS. */ - getLocationAbsUrl(): webdriver.promise.Promise; + getLocationAbsUrl(): webdriver.promise.Promise; /** * Pauses the test and injects some helper functions into the browser, so that @@ -1057,6 +1707,7 @@ declare module protractor { * 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 @@ -1076,11 +1727,27 @@ declare module protractor { * point in the control flow. * Does not require changes to the command line (no need to add 'debug'). * - * @param {=number} opt_debugPort Optional port to use for the debugging process + * @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; + } - //endregion + // 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; } /** @@ -1091,19 +1758,6 @@ declare module protractor { * @return {Protractor} */ function wrapDriver(webdriver: webdriver.WebDriver, opt_baseUrl?: string, opt_rootElement?: string): Protractor; - - /** - * Set a singleton instance of protractor. - * @param {Protractor} ptor - */ - function setInstance(ptor: Protractor): void; - - /** - * Get the singleton instance. - * @return {Protractor} - */ - function getInstance(): Protractor; - } interface cssSelectorHelper { @@ -1114,8 +1768,9 @@ interface cssArraySelectorHelper { (cssLocator: string): protractor.ElementArrayFinder; } -declare var browser: protractor.Protractor; +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; diff --git a/angular-protractor/legacy/angular-protractor-0.17.0-tests.ts b/angular-protractor/legacy/angular-protractor-0.17.0-tests.ts deleted file mode 100644 index dfd413d0e0..0000000000 --- a/angular-protractor/legacy/angular-protractor-0.17.0-tests.ts +++ /dev/null @@ -1,244 +0,0 @@ -/// - -function TestWebDriverExports() { - var abstractBuilder: protractor.AbstractBuilder = new protractor.AbstractBuilder(); - var baseAbstractBuilder: webdriver.AbstractBuilder = abstractBuilder; - - var button: protractor.Button = new protractor.Button(); - var baseButton: webdriver.Button = button; - - 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 alert: protractor.Alert = new protractor.Alert(driver, 'Message'); - var baseAlert: webdriver.Alert = alert; - - var unhandledAlertError: protractor.UnhandledAlertError = new protractor.UnhandledAlertError('Message', alert); - var baseUnhandledAlertError: webdriver.UnhandledAlertError = unhandledAlertError; - - 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 firefoxDomExecutor: protractor.FirefoxDomExecutor = new protractor.FirefoxDomExecutor(); - var baseFirefoxDomExecutor: webdriver.FirefoxDomExecutor = firefoxDomExecutor; - - var webElement: protractor.WebElement = new protractor.WebElement(driver, new protractor.promise.Promise()); - var baseWebElement: webdriver.WebElement = webElement; - - var locator: protractor.Locator = new protractor.Locator('id', 'ABC'); - var baseLocator: webdriver.Locator = locator; - - var session: protractor.Session = new protractor.Session('ABC', webdriver.Capabilities.android()); - var baseSession: webdriver.Session = session; - - locator = protractor.By.name('name'); - - // logging module - - var levelName: string = protractor.logging.LevelName.ALL; - var loggingType: string = protractor.logging.Type.CLIENT; - - var level: webdriver.logging.Level = 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'); - - protractor.logging.Preferences = { a: 123 }; - - // promise module - - 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; - - 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; }); - - flow = protractor.promise.controlFlow(); - - promise = protractor.promise.createFlow(function(newFlow: webdriver.promise.ControlFlow) { }); - - deferred = protractor.promise.defer(function() {}); - deferred = protractor.promise.defer(function(reason?: any) {}); - - promise = protractor.promise.delayed(123); - - promise = protractor.promise.fulfilled(); - promise = protractor.promise.fulfilled({a: 123}); - - promise = protractor.promise.fullyResolved({a: 123}); - - var isPromise: 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; }); - - // error module - - 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; - - // process module - - var isNative: boolean = protractor.process.isNative(); - var value: string; - - value = protractor.process.getEnv('name'); - value = protractor.process.getEnv('name', 'default'); - - protractor.process.setEnv('name', 'value'); - protractor.process.setEnv('name', 123); - -} - -function TestProtractor() { - var ptor: protractor.Protractor; - var driver: webdriver.WebDriver = new webdriver.Builder(). - withCapabilities(webdriver.Capabilities.chrome()). - build(); - - ptor = new protractor.Protractor(driver); - ptor = new protractor.Protractor(driver, 'baseUrl'); - ptor = new protractor.Protractor(driver, 'baseUrl', 'rootElement'); - ptor = protractor.getInstance(); - protractor.setInstance(ptor); - - ptor = protractor.wrapDriver(driver); - ptor = protractor.wrapDriver(driver, 'baseUrl'); - ptor = protractor.wrapDriver(driver, 'baseUrl', 'rootElement'); - - ptor = browser; - - driver = ptor.driver; - var baseUrl: string = ptor.baseUrl; - var rootEl: string = ptor.rootEl; - var ignoreSynchronization: boolean = ptor.ignoreSynchronization; - var params: any = ptor.params; - - ptor.debugger(); - - ptor.clearMockModules(); - ptor.addMockModule('name', 'script'); - ptor.addMockModule('name', function() {}); - ptor.waitForAngular(); - - var elementFinder: protractor.ElementFinder; - - elementFinder = ptor.element(by.id('ABC')); - elementFinder = ptor.$('.class'); - - var elementArrayFinder: protractor.ElementArrayFinder = ptor.$$('.class'); - - var webElement: webdriver.WebElement = ptor.wrapWebElement(new webdriver.WebElement(driver, 'id')); - - var locationAbsUrl: webdriver.promise.Promise = ptor.getLocationAbsUrl(); -} - -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 promise: webdriver.promise.Promise; - - promise = elementFinder.click(); - promise = elementFinder.sendKeys(protractor.Key.UP, protractor.Key.DOWN); - promise = elementFinder.getTagName(); - promise = elementFinder.getCssValue('display'); - promise = elementFinder.getAttribute('atribute'); - promise = elementFinder.getText(); - promise = elementFinder.getSize(); - promise = elementFinder.getLocation(); - promise = elementFinder.isEnabled(); - promise = elementFinder.isSelected(); - promise = elementFinder.submit(); - promise = elementFinder.clear(); - promise = elementFinder.isDisplayed(); - promise = elementFinder.getOuterHtml(); - promise = elementFinder.getInnerHtml(); - promise = elementFinder.isElementPresent(by.id('id')); - promise = elementFinder.isElementPresent(by.js('function(a, b, c) {}'), 1, 2, 3); - promise = elementFinder.findElements(by.className('class')); - promise = elementFinder.findElements(by.js('function(a, b, c) {}'), 1, 2, 3); - promise = elementFinder.$$('.class'); - promise = elementFinder.evaluate('expression'); - promise = elementFinder.isPresent(); - - var webElement: webdriver.WebElement; - - webElement = elementFinder.$('.class'); - webElement = elementFinder.findElement(by.id('id')); - webElement = elementFinder.findElement(by.js('function(a, b, c) {}'), 1, 2, 3); - webElement = elementFinder.find(); -} - -// This function tests the angular specific locator strategies. -function TestLocatorStrategies() { - var ptor: protractor.Protractor = protractor.getInstance(); - var webElement: webdriver.WebElement; - - // Protractor Specific Locators - webElement = ptor.findElement(protractor.By.binding('binding')); - webElement = ptor.findElement(protractor.By.select('select')); - webElement = ptor.findElement(protractor.By.selectedOption('selectedOptions')); - webElement = ptor.findElement(protractor.By.input('input')); - webElement = ptor.findElement(protractor.By.model('model')); - webElement = ptor.findElement(protractor.By.textarea('textarea')); - webElement = ptor.findElement(protractor.By.repeater('repeater')); - webElement = ptor.findElement(protractor.By.buttonText('buttonText')); - webElement = ptor.findElement(protractor.By.partialButtonText('partialButtonText')); -} - -// This function tests the methods that were added to the base WebElement class -function TestWebElements() { - var ptor: protractor.Protractor = protractor.getInstance(); - - var webElement: protractor.WebElement; - var promise: webdriver.promise.Promise; - - webElement = ptor.findElement(by.id('id')).$('.class'); - promise = ptor.findElement(by.id('id')).$$('.class'); - promise = ptor.findElement(by.id('id')).evaluate('something'); - - webElement = webElement.findElement(by.id('id')).$('.class'); - promise = webElement.findElement(by.id('id')).$$('.class'); - promise = webElement.findElement(by.id('id')).evaluate('something'); -} diff --git a/angular-protractor/legacy/angular-protractor-0.17.0.d.ts b/angular-protractor/legacy/angular-protractor-0.17.0.d.ts deleted file mode 100644 index 38458b4933..0000000000 --- a/angular-protractor/legacy/angular-protractor-0.17.0.d.ts +++ /dev/null @@ -1,906 +0,0 @@ -// Type definitions for Angular Protractor 0.17.0 -// Project: https://github.com/angular/protractor -// Definitions by: Bill Armstrong -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module protractor { - //region Wrapped webdriver Items - - class AbstractBuilder extends webdriver.AbstractBuilder {} - class ActionSequence extends webdriver.ActionSequence {} - class Alert extends webdriver.Alert {} - class Builder extends webdriver.Builder {} - class Button extends webdriver.Button {} - class Capabilities extends webdriver.Capabilities {} - class Command extends webdriver.Command {} - class EventEmitter extends webdriver.EventEmitter {} - class FirefoxDomExecutor extends webdriver.FirefoxDomExecutor {} - class Locator extends webdriver.Locator {} - class Session extends webdriver.Session {} - class WebDriver extends webdriver.WebDriver {} - class Browser extends webdriver.Browser {} - class Capability extends webdriver.Capability {} - class CommandName extends webdriver.CommandName {} - class Key extends webdriver.Key {} - class UnhandledAlertError extends webdriver.UnhandledAlertError {} - - class WebElement extends webdriver.WebElement { - /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElement - * @return {!protractor.WebElement} - */ - $(selector: string): protractor.WebElement; - - /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElements - * @return {!webdriver.promise.Promise} A promise that will be resolved to an - * array of the located {@link webdriver.WebElement}s. - */ - $$(selector: string): webdriver.promise.Promise; - - /** - * Evalates the input as if it were on the scope of the current element. - * @param {string} expression - * - * @return {!webdriver.promise.Promise} A promise that will resolve to the - * evaluated expression. 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): webdriver.promise.Promise; - - /** - * Schedule a command to find a descendant of this element. If the element - * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will - * be returned by the driver. Unlike other commands, this error cannot be - * suppressed. In other words, scheduling a command to find an element doubles - * as an assert that the element is present on the page. To test whether an - * element is present on the page, use {@code #isElementPresent} instead. - *

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

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

- * Note that JS locator searches cannot be restricted to a subtree. All such - * searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {protractor.WebElement} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. - */ - findElement(locator: webdriver.Locator, ...var_args: any[]): protractor.WebElement; - findElement(locator: any, ...var_args: any[]): protractor.WebElement; - } - - module command { - class Command extends webdriver.Command {} - class CommandName extends webdriver.CommandName {} - } - - module error { - class Error extends webdriver.error.Error {} - class ErrorCode extends webdriver.error.ErrorCode {} - } - - module events { - class EventEmitter extends webdriver.EventEmitter {} - } - - module logging { - var Preferences: any; - - class LevelName extends webdriver.logging.LevelName {} - class Type extends webdriver.logging.Type {} - class Level extends webdriver.logging.Level {} - class Entry extends webdriver.logging.Entry {} - - function getLevel(nameOrValue: string): webdriver.logging.Level; - function getLevel(nameOrValue: number): webdriver.logging.Level; - } - - module promise { - class Promise extends webdriver.promise.Promise {} - class Deferred extends webdriver.promise.Deferred {} - class ControlFlow extends webdriver.promise.ControlFlow {} - - /** - * @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) => any): 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; - - /** - * 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; - - /** - * Creates a new deferred object. - * @param {Function=} opt_canceller Function to call when cancelling the - * computation of this instance's value. - * @return {!webdriver.promise.Deferred} The new deferred object. - */ - function defer(opt_canceller?: any): 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?: 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: (error: any, value: any) => 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: any, opt_callback?: (value: any) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise; - - /** - * Invokes the appropriate callback function as soon as a promised - * {@code value} is resolved. This function is similar to - * {@code 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: (value: any) => any, opt_errback?: (error: any) => any): void; - - /** - * 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; - - } - - module process { - - /** - * Queries for a named environment variable. - * @param {string} name The name of the environment variable to look up. - * @param {string=} opt_default The default value if the named variable is not - * defined. - * @return {string} The queried environment variable. - */ - function getEnv(name: string, opt_default?: string): string; - - /** - * @return {boolean} Whether the current process is Node's native process - * object. - */ - function isNative(): boolean; - - /** - * Sets an environment value. If the new value is either null or undefined, the - * environment variable will be cleared. - * @param {string} name The value to set. - * @param {*} value The new value; will be coerced to a string. - */ - function setEnv(name: string, value: any): void; - - } - - //endregion - - interface Element { - (locator: webdriver.Locator): ElementFinder; - all(locator: webdriver.Locator): ElementArrayFinder; - } - - interface ElementFinder { - /** - * 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; - - /** - * 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; - - /** - * Schedules a command to test if there is at least one descendant of this - * element that matches the given search criteria. - * - *

Note that JS locator searches cannot be restricted to a subtree of the - * DOM. All such searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether an element could be located on the page. - */ - isElementPresent(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; - isElementPresent(locator: any, ...var_args: any[]): webdriver.promise.Promise; - - /** - * Schedules a command to find all of the descendants of this element that match - * the given search criteria. - *

- * Note that JS locator searches cannot be restricted to a subtree. All such - * searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the elements. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {!webdriver.promise.Promise} A promise that will be resolved with an - * array of located {@link webdriver.WebElement}s. - */ - findElements(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; - findElements(locator: any, ...var_args: any[]): webdriver.promise.Promise; - - /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElement - * @return {!protractor.WebElement} - */ - $(selector: string): protractor.WebElement; - - /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElements - * @return {!webdriver.promise.Promise} A promise that will be resolved to an - * array of the located {@link webdriver.WebElement}s. - */ - $$(selector: string): webdriver.promise.Promise; - - /** - * Schedule a command to find a descendant of this element. If the element - * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will - * be returned by the driver. Unlike other commands, this error cannot be - * suppressed. In other words, scheduling a command to find an element doubles - * as an assert that the element is present on the page. To test whether an - * element is present on the page, use {@code #isElementPresent} instead. - *

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

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

- * Note that JS locator searches cannot be restricted to a subtree. All such - * searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {protractor.WebElement} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. - */ - findElement(locator: webdriver.Locator, ...var_args: any[]): protractor.WebElement; - findElement(locator: any, ...var_args: any[]): protractor.WebElement; - - /** - * Evalates the input as if it were on the scope of the current element. - * @param {string} expression - * - * @return {!webdriver.promise.Promise} A promise that will resolve to the - * evaluated expression. 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): webdriver.promise.Promise; - - /** - * Use as: element(locator).element(locator) - * Calls to element may be chained to find elements within a parent. - * - * @param {webdriver.Locator} The locator that will be used to find descendents. - * - * @return {protractor.ElementFinder} the descendent element found by the locator - */ - element(locator: webdriver.Locator): protractor.ElementFinder; - - /** - * Use as: element(locator).all(locator) - * Calls to element may be chained to find an array of elements within a parent. - * - * @param {webdriver.Locator} The locator that will be used to find descendents. - * - * @return {protractor.ElementArrayFinder} the descendent elements found by the locator - */ - all(locator: webdriver.Locator): protractor.ElementArrayFinder; - - find(): protractor.WebElement; - - isPresent(): webdriver.promise.Promise; - } - - interface ElementArrayFinder{ - count(): webdriver.promise.Promise; - get(index: number): protractor.WebElement; - first(): protractor.WebElement; - last(): protractor.WebElement; - then(fn: (value: any) => any): webdriver.promise.Promise; - } - - class LocatorWithColumn extends webdriver.Locator { - column(index: number): webdriver.Locator; - } - - class RepeaterLocator extends LocatorWithColumn { - row(index: number): LocatorWithColumn; - } - - interface IProtractorLocatorStrategy extends webdriver.ILocatorStrategy { - /** - * Add a locator to this instance of ProtractorBy. This locator can then be - * used with element(by.()). - * - * @param {string} name - * @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 begins with the element scoping the search, and then - * contains any args passed into the locator. It should return - * an array of elements. - */ - addLocator(name: string, script: any): void; - - /** - * Usage: - * {{status}} - * var status = element(by.binding('{{status}}')); - */ - binding(bindingDescriptor: string): webdriver.Locator; - - /** - * Usage: - * - * element(by.select("user")); - */ - select(model: string): webdriver.Locator; - - /** - * Usage: - * - * element(by.selectedOption("user")); - */ - selectedOption(model: string): webdriver.Locator; - - /** - * @DEPRECATED - use 'model' instead. - * Usage: - * - * element(by.input('user')); - */ - input(model: string): webdriver.Locator; - - /** - * Usage: - * - * element(by.model('user')); - */ - model(model: string): webdriver.Locator; - - /** - * Usage: - * - * element(by.textarea("user")); - */ - textarea(model: string): webdriver.Locator; - - /** - * Usage: - *

- * {{cat.name}} - * {{cat.age}} - *
- * - * // Returns the DIV for the second cat. - * var secondCat = element(by.repeater("cat in pets").row(2)); - * // Returns the SPAN for the first cat's name. - * var firstCatName = element( - * by.repeater("cat in pets").row(1).column("{{cat.name}}")); - * // Returns a promise that resolves to an array of WebElements from a column - * var ages = element( - * by.repeater("cat in pets").column("{{cat.age}}")); - * // Returns a promise that resolves to an array of WebElements containing - * // all rows of the repeater. - * var rows = element(by.repeater("cat in pets")); - */ - repeater(repeatDescriptor: string): RepeaterLocator; - - buttonText(searchText: string): webdriver.Locator; - - partialButtonText(searchText: string): webdriver.Locator; - } - - var By: IProtractorLocatorStrategy; - - class Protractor extends webdriver.WebDriver { - - //region Constructors - - /** - * @param {webdriver.WebDriver} webdriver - * @param {string=} opt_baseUrl A base URL to run get requests against. - * @param {string=body} opt_rootElement Selector element that has an ng-app in - * scope. - * @constructor - */ - constructor(webdriver: webdriver.WebDriver, opt_baseUrl?: string, opt_rootElement?: string); - - //endregion - - //region Properties - - /** - * 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; - - /** - * 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; - - /** - * An object that holds custom test parameters. - * - * @type {Object} - */ - params: any; - - //endregion - - //region Methods - - /** - * Helper function for finding elements. - * - * @type {function(webdriver.Locator): ElementFinder} - */ - element(locator: webdriver.Locator): ElementFinder; - - /** - * Helper function for finding elements by css. - * - * @type {function(string): ElementFinder} - */ - $(cssLocator: string): ElementFinder; - - /** - * Helper function for finding arrays of elements by css. - * - * @type {function(string): ElementArrayFinder} - */ - $$(cssLocator: string): ElementArrayFinder; - - /** - * 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; - - /** - * Wrap a webdriver.WebElement with protractor specific functionality. - * - * @param {webdriver.WebElement} element - * @return {protractor.WebElement} the wrapped web element. - */ - wrapWebElement(element: webdriver.WebElement): protractor.WebElement; - - /** - * 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. - * - * @param {!string} name The name of the module to load or override. - * @param {!string|Function} script The JavaScript to load the module. - */ - addMockModule(name: string, script: string): void; - addMockModule(name: string, script: any): void; - - /** - * Clear the list of registered mock modules. - */ - clearMockModules(): void; - - /** - * 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 - * - * 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; - - /** - * Schedule a command to find an element on the page. If the element cannot be - * found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned - * by the driver. Unlike other commands, this error cannot be suppressed. In - * other words, scheduling a command to find an element doubles as an assert - * that the element is present on the page. To test whether an element is - * present on the page, use {@code #isElementPresent} instead. - * - *

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

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

When running in the browser, a WebDriver cannot manipulate DOM elements - * directly; it may do so only through a {@link webdriver.WebElement} reference. - * This function may be used to generate a WebElement from a DOM element. A - * reference to the DOM element will be stored in a known location and this - * driver will attempt to retrieve it through {@link #executeScript}. If the - * element cannot be found (eg, it belongs to a different document than the - * one this instance is currently focused on), a - * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. - * - * @param {!(webdriver.Locator|Object.|Element)} locatorOrElement The - * locator strategy to use when searching for the element, or the actual - * DOM element to be located by the server. - * @param {...} var_args Arguments to pass to {@code #executeScript} if using a - * JavaScript locator. Otherwise ignored. - * @return {!protractor.WebElement} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. - */ - findElement(locatorOrElement: webdriver.Locator, ...var_args: any[]): protractor.WebElement; - findElement(locatorOrElement: any, ...var_args: any[]): protractor.WebElement; - - //endregion - } - - /** - * 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; - - /** - * Set a singleton instance of protractor. - * @param {Protractor} ptor - */ - function setInstance(ptor: Protractor): void; - - /** - * Get the singleton instance. - * @return {Protractor} - */ - function getInstance(): Protractor; - -} - -interface cssSelectorHelper { - (cssLocator: string): protractor.ElementFinder; -} - -declare var browser: protractor.Protractor; -declare var by: protractor.IProtractorLocatorStrategy; -declare var element: protractor.Element; -declare var $: cssSelectorHelper; -declare var $$: cssSelectorHelper; - -declare module 'protractor' { - export = protractor; -} diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 52b317d961..467a01d3b5 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -1,28 +1,131 @@ /// -function TestAbstractBuilder() { - var builder: webdriver.AbstractBuilder = new webdriver.AbstractBuilder(); - var driver: webdriver.WebDriver = builder.build(); - var capabilities: webdriver.Capabilities = builder.getCapabilities(); - url = builder.getServerUrl(); - var otherBuilder: webdriver.AbstractBuilder = builder.usingServer(url); - otherBuilder = builder.withCapabilities(webdriver.Capabilities.android()); - var objCapabilities: { [index: string]: string; } = {}; - objCapabilities[webdriver.Capability.BROWSER_NAME] = webdriver.Browser.PHANTOM_JS; - otherBuilder = builder.withCapabilities(objCapabilities); - var url: string = webdriver.AbstractBuilder.DEFAULT_SERVER_URL; - var env: string = webdriver.AbstractBuilder.SERVER_URL_ENV; +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()); + + var baseDriver: webdriver.WebDriver = driver; +} + +function TestChromeOptions() { + var options: chrome.Options = new chrome.Options(); + options = chrome.Options.fromCapabilities(webdriver.Capabilities.chrome()); + + options = options.addArguments("a", "b", "c"); + options = options.addExtensions("a", "b", "c"); + options = options.detachDriver(true); + options = options.setChromeBinaryPath("path"); + options = options.setChromeLogFile("logfile"); + options = options.setLocalState("state"); + options = options.setLoggingPrefs(new webdriver.logging.Preferences()); + options = options.setProxy({ proxyType: "proxyType" }); + options = options.setUserPreferences("preferences"); + var capabilities: webdriver.Capabilities = options.toCapabilities(); + capabilities = options.toCapabilities(webdriver.Capabilities.chrome()); + var values: chrome.IOptionsValues = options.toJSON(); +} + +function TestServiceBuilder() { + var builder: chrome.ServiceBuilder = new chrome.ServiceBuilder(); + builder = new chrome.ServiceBuilder("exe"); + + var anything: any = builder.build(); + builder = builder.enableVerboseLogging(); + builder = builder.loggingTo("path"); + builder = builder.setNumHttpThreads(5); + builder = builder.setStdio("config"); + builder = builder.setStdio(["A", "B"]); + builder = builder.setUrlBasePath("path"); + builder = builder.usingPort(8080); + builder = builder.withEnvironment({ "A": "a", "B": "b" }); +} + +function TestChromeModule() { + var service: any = chrome.getDefaultService(); + chrome.setDefaultService({}); +} + +function TestBinary() { + var binary: firefox.Binary = new firefox.Binary(); + binary = new firefox.Binary("exe"); + + binary.addArguments("A", "B", "C"); + var promise: webdriver.promise.Promise = binary.kill(); + binary.launch("profile").then(function (result: any) { }); +} + +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()); + + var baseDriver: webdriver.WebDriver = driver; +} + +function TestFirefoxOptions() { + var options: firefox.Options = new firefox.Options(); + + options = options.setBinary("binary"); + options = options.setBinary(new firefox.Binary()); + options = options.setLoggingPreferences(new webdriver.logging.Preferences()); + options = options.setProfile("profile"); + 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() { + var profile: firefox.Profile = new firefox.Profile(); + profile = new firefox.Profile("dir"); + + var bool: boolean = profile.acceptUntrustedCerts(); + profile.addExtension("ext"); + bool = profile.assumeUntrustedCertIssuer(); + profile.encode().then(function (prof: string) { }); + var num: number = profile.getPort(); + var anything: any = profile.getPreference("key"); + bool = profile.nativeEventsEnabled(); + profile.setAcceptUntrustedCerts(true); + profile.setAssumeUntrustedCertIssuer(true); + profile.setNativeEventsEnabled(true); + profile.setPort(8080); + profile.setPreference("key", "value"); + profile.setPreference("key", 5); + profile.setPreference("key", true); + var stringPromise: webdriver.promise.Promise = profile.writeToDisk(); + stringPromise = profile.writeToDisk(true); +} + +function TestExecutors() { + var exec: webdriver.CommandExecutor = executors.createExecutor("url"); + exec = executors.createExecutor(new webdriver.promise.Promise()); } function TestBuilder() { var builder: webdriver.Builder = new webdriver.Builder(); - var abstractBuilder: webdriver.AbstractBuilder = builder; var driver: webdriver.WebDriver = builder.build(); - var session: string = builder.getSession(); - abstractBuilder = builder.usingSession("ID"); + builder = builder.forBrowser('name'); + builder = builder.forBrowser('name', 'version'); + builder = builder.forBrowser('name', 'version', 'platform'); - var env: string = webdriver.Builder.SESSION_ID_ENV; + var cap: webdriver.Capabilities = builder.getCapabilities(); + var str:string = builder.getServerUrl(); + + builder = builder.setAlertBehavior('behavior'); + builder = builder.setChromeOptions(new chrome.Options()); + builder = builder.setControlFlow(new webdriver.promise.ControlFlow()); + builder = builder.setEnableNativeEvents(true); + builder = builder.setFirefoxOptions(new firefox.Options()); + builder = builder.setLoggingPrefs(new webdriver.logging.Preferences()); + builder = builder.setLoggingPrefs({ "key": "value" }); + builder = builder.setProxy({ proxyType: 'type' }); + builder = builder.setScrollBehavior(1); + builder = builder.usingServer('http://someserver'); + builder = builder.withCapabilities(new webdriver.Capabilities()); + builder = builder.withCapabilities({ something: true }); } function TestActionSequence() { @@ -31,7 +134,7 @@ function TestActionSequence() { build(); var sequence: webdriver.ActionSequence = new webdriver.ActionSequence(driver); - var element: webdriver.WebElement = new webdriver.WebElement(driver, 'id'); + var element: webdriver.WebElement = new webdriver.WebElement(driver, { ELEMENT: 'id' }); // Click sequence = sequence.click(); @@ -76,23 +179,20 @@ function TestActionSequence() { sequence = sequence.sendKeys("A", "B", "C"); sequence = sequence.sendKeys(["A", "B", "C"]); - var promise: webdriver.promise.Promise = sequence.perform(); + sequence.perform().then(function () { }); } function TestAlert() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). build(); - var promise: webdriver.promise.Promise = new webdriver.promise.Promise(); - var alert: webdriver.Alert = new webdriver.Alert(driver, 'ABC'); - alert = new webdriver.Alert(driver, promise); - var deferred: webdriver.promise.Deferred = alert; + var alert: webdriver.Alert = driver.switchTo().alert(); - promise = alert.accept(); - promise = alert.dismiss(); - promise = alert.getText(); - promise = alert.sendKeys("ABC"); + alert.accept().then(function () { }); + alert.dismiss().then(function () { }); + alert.getText().then(function (text: string) { }); + alert.sendKeys("ABC").then(function () { }); } function TestBrowser() { @@ -131,6 +231,12 @@ function TestCapabilities() { capabilities = capabilities.merge(objCapabilities); capabilities = capabilities.set(webdriver.Capability.VERSION, { abc: 'def' }); capabilities = capabilities.set(webdriver.Capability.VERSION, null); + capabilities = capabilities.setLoggingPrefs(new webdriver.logging.Preferences()); + capabilities = capabilities.setLoggingPrefs({ "key": "value" }); + capabilities = capabilities.setProxy({ proxyType: 'Type' }); + capabilities = capabilities.setEnableNativeEvents(true); + capabilities = capabilities.setScrollBehavior(1); + capabilities = capabilities.setAlertBehavior('accept'); anything = capabilities.toJSON(); @@ -152,14 +258,15 @@ function TestCapability() { capability = webdriver.Capability.ACCEPT_SSL_CERTS; capability = webdriver.Capability.BROWSER_NAME; + capability = webdriver.Capability.ELEMENT_SCROLL_BEHAVIOR; capability = webdriver.Capability.HANDLES_ALERTS; capability = webdriver.Capability.LOGGING_PREFS; + capability = webdriver.Capability.NATIVE_EVENTS; capability = webdriver.Capability.PLATFORM; capability = webdriver.Capability.PROXY; capability = webdriver.Capability.ROTATABLE; capability = webdriver.Capability.SECURE_SSL; capability = webdriver.Capability.SUPPORTS_APPLICATION_CACHE; - capability = webdriver.Capability.SUPPORTS_BROWSER_CONNECTION; capability = webdriver.Capability.SUPPORTS_CSS_SELECTORS; capability = webdriver.Capability.SUPPORTS_JAVASCRIPT; capability = webdriver.Capability.SUPPORTS_LOCATION_CONTEXT; @@ -181,7 +288,8 @@ function TestCommand() { } function TestCommandExecutor() { - var c: webdriver.CommandExecutor = { execute: function(command: webdriver.Command, callback: (error: Error, obj: any) => any) {} }; + 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 TestCommandName() { @@ -291,10 +399,14 @@ function TestEventEmitter() { var callback = function (a: number, b: number, c: number) {}; emitter = emitter.addListener('ABC', callback); + emitter = emitter.addListener('ABC', callback, this); emitter.emit('ABC', 1, 2, 3); var listeners = emitter.listeners('ABC'); + if (listeners[0].oneshot) { + listeners[0].fn.apply(listeners[0].scope); + } var length: number = listeners.length; var listenerInfo = listeners[0]; if (listenerInfo.oneshot) { @@ -302,8 +414,10 @@ function TestEventEmitter() { } emitter = emitter.on('ABC', callback); + emitter = emitter.on('ABC', callback, this); emitter = emitter.once('ABC', callback); + emitter = emitter.once('ABC', callback, this); emitter = emitter.removeListener('ABC', callback); @@ -311,14 +425,6 @@ function TestEventEmitter() { emitter.removeAllListeners(); } -function TestFirefoxDomExecutor() { - if (webdriver.FirefoxDomExecutor.isAvailable()) { - var executor: webdriver.CommandExecutor = new webdriver.FirefoxDomExecutor(); - var callback = function(error: Error, responseObject: any) {}; - executor.execute(new webdriver.Command(webdriver.CommandName.CLICK), callback); - } -} - function TestKey() { var key: string; @@ -387,21 +493,28 @@ function TestKey() { } function TestLocator() { - var locator: webdriver.Locator = new webdriver.Locator('id', 'ABC'); + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var locator: webdriver.Locator = webdriver.By.className('class'); var locatorStr: string = locator.toString(); var using: string = locator.using; var value: string = locator.value; - locator = webdriver.Locator.checkLocator(webdriver.Locator.Strategy.id('ABC')); - locator = webdriver.Locator.checkLocator({id: 'ABC'}); + var str: string = locator.toString(); - locator = webdriver.Locator.createFromObj({id: 'ABC'}); + locator = webdriver.By.css('css'); + locator = webdriver.By.id('id'); + locator = webdriver.By.linkText('link'); + locator = webdriver.By.name('name'); + locator = webdriver.By.partialLinkText('text'); + locator = webdriver.By.tagName('tag'); + locator = webdriver.By.xpath('xpath'); - locator = webdriver.Locator.Strategy.id('ABC'); - - locator = webdriver.By.id('ABC'); + webdriver.By.js('script', 1, 2, 3)(driver).then(function (abc: number) { }); } function TestSession() { @@ -418,16 +531,13 @@ function TestSession() { } function TestUnhandledAlertError() { - var driver: webdriver.WebDriver = new webdriver.Builder(). - withCapabilities(webdriver.Capabilities.chrome()). - build(); - var promise: webdriver.promise.Promise = new webdriver.promise.Promise(); + var someFunc = function (error: webdriver.UnhandledAlertError) { + var baseError: webdriver.error.Error = error; - var alert: webdriver.Alert = new webdriver.Alert(driver, 'ABC'); - var error = new webdriver.UnhandledAlertError('An error', alert); - var baseError: webdriver.error.Error = error; - - alert = error.getAlert(); + var alert: webdriver.Alert = error.getAlert(); + var str: string = error.getAlertText(); + str = error.toString(); + } } function TestWebDriverLogs() { @@ -435,11 +545,10 @@ function TestWebDriverLogs() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var logs: webdriver.WebDriverLogs = webdriver.WebDriver.Logs; - var promise: webdriver.promise.Promise; + var logs: webdriver.WebDriverLogs = new webdriver.WebDriver.Logs(driver); - promise = logs.get(webdriver.logging.Type.BROWSER); - promise = logs.getAvailableLogTypes(); + logs.get(webdriver.logging.Type.BROWSER).then(function (entries: webdriver.logging.Entry[]) { });; + logs.getAvailableLogTypes().then(function (types: string[]) { }); } function TestWebDriverNavigation() { @@ -447,13 +556,12 @@ function TestWebDriverNavigation() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var navigation: webdriver.WebDriverNavigation = webdriver.WebDriver.Navigation; - var promise: webdriver.promise.Promise; + var navigation: webdriver.WebDriverNavigation = new webdriver.WebDriver.Navigation(driver); - promise = navigation.back(); - promise = navigation.forward(); - promise = navigation.refresh(); - promise = navigation.to('http://google.com'); + navigation.back().then(function () { }); + navigation.forward().then(function () { }); + navigation.refresh().then(function () { }); + navigation.to('http://google.com').then(function () { }); } function TestWebDriverOptions() { @@ -461,8 +569,8 @@ function TestWebDriverOptions() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var options: webdriver.WebDriverOptions = webdriver.WebDriver.Options; - var promise: webdriver.promise.Promise; + var options: webdriver.WebDriverOptions = new webdriver.WebDriver.Options(driver); + var promise: webdriver.promise.Promise; // Add Cookie promise = options.addCookie('name', 'value'); @@ -474,8 +582,8 @@ function TestWebDriverOptions() { promise = options.deleteAllCookies(); promise = options.deleteCookie('name'); - promise = options.getCookie('name'); - promise = options.getCookies(); + 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(); @@ -487,8 +595,8 @@ function TestWebDriverTargetLocator() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var locator: webdriver.WebDriverTargetLocator = webdriver.WebDriver.TargetLocator; - var promise: webdriver.promise.Promise; + var locator: webdriver.WebDriverTargetLocator = new webdriver.WebDriver.TargetLocator(driver); + var promise: webdriver.promise.Promise; var element: webdriver.WebElement = locator.activeElement(); var alert: webdriver.Alert = locator.alert(); @@ -503,8 +611,8 @@ function TestWebDriverTimeouts() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var timeouts: webdriver.WebDriverTimeouts = webdriver.WebDriver.Timeouts; - var promise: webdriver.promise.Promise; + var timeouts: webdriver.WebDriverTimeouts = new webdriver.WebDriver.Timeouts(driver); + var promise: webdriver.promise.Promise; promise = timeouts.implicitlyWait(123); promise = timeouts.pageLoadTimeout(123); @@ -516,85 +624,92 @@ function TestWebDriverWindow() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var window: webdriver.WebDriverWindow = webdriver.WebDriver.Window; - var promise: webdriver.promise.Promise; + var window: webdriver.WebDriverWindow = new webdriver.WebDriver.Window(driver); + var locationPromise: webdriver.promise.Promise; + var sizePromise: webdriver.promise.Promise; + var voidPromise: webdriver.promise.Promise; - promise = window.getPosition(); - promise = window.getSize(); - promise = window.maximize(); - promise = window.setPosition(12, 34); - promise = window.setSize(12, 34); + locationPromise = window.getPosition(); + sizePromise = window.getSize(); + voidPromise = window.maximize(); + voidPromise = window.setPosition(12, 34); + voidPromise = window.setSize(12, 34); } function TestWebDriver() { var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); - var promise: webdriver.promise.Promise = new webdriver.promise.Promise(); - var executor: webdriver.CommandExecutor = new webdriver.FirefoxDomExecutor(); + var sessionPromise: webdriver.promise.Promise = new webdriver.promise.Promise(); + var executor: webdriver.CommandExecutor = 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); - driver = new webdriver.WebDriver(promise, executor); - driver = new webdriver.WebDriver(promise, executor, flow); + driver = new webdriver.WebDriver(sessionPromise, executor); + driver = new webdriver.WebDriver(sessionPromise, executor, flow); + + var voidPromise: webdriver.promise.Promise; + var stringPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; - // Call var actions: webdriver.ActionSequence = driver.actions(); - promise = driver.call(function(){}); - promise = driver.call(function(){ var d: any = this;}, driver); - promise = driver.call(function(a: number){}, driver, 1); - promise = driver.close(); + // call + stringPromise = driver.call(function(){}); + stringPromise = driver.call(function(){ var d: any = this;}, driver); + stringPromise = driver.call(function(a: number){}, driver, 1); + + voidPromise = driver.close(); flow = driver.controlFlow(); - // ExecuteAsyncScript - promise = driver.executeAsyncScript('function(){}'); - promise = driver.executeAsyncScript('function(){}', 1, 2, 3); - promise = driver.executeAsyncScript(function(){}); - promise = driver.executeAsyncScript(function(a: number){}, 1); + // executeAsyncScript + stringPromise = driver.executeAsyncScript('function(){}'); + stringPromise = driver.executeAsyncScript('function(){}', 1, 2, 3); + stringPromise = driver.executeAsyncScript(function(){}); + stringPromise = driver.executeAsyncScript(function(a: number){}, 1); - // ExecuteScript - promise = driver.executeScript('function(){}'); - promise = driver.executeScript('function(){}', 1, 2, 3); - promise = driver.executeScript(function(){}); - promise = driver.executeScript(function(a: number){}, 1); + // executeScript + stringPromise = driver.executeScript('function(){}'); + stringPromise = driver.executeScript('function(){}', 1, 2, 3); + stringPromise = driver.executeScript(function(){}); + stringPromise = driver.executeScript(function(a: number){}, 1); + // findElement var element: webdriver.WebElement; element = driver.findElement(webdriver.By.id('ABC')); element = driver.findElement({id: 'ABC'}); element = driver.findElement(webdriver.By.js('function(){}'), 1, 2, 3); element = driver.findElement({js: 'function(){}'}, 1, 2, 3); - promise = driver.findElements(webdriver.By.className('ABC')); - promise = driver.findElements({className: 'ABC'}); - promise = driver.findElements(webdriver.By.js('function(){}'), 1, 2, 3); - promise = driver.findElements({js: 'function(){}'}, 1, 2, 3); + // 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(){}'), 1, 2, 3).then(function (elements: webdriver.WebElement[]) { }); + driver.findElements({ js: 'function(){}' }, 1, 2, 3).then(function (elements: webdriver.WebElement[]) { }); - promise = driver.get('http://www.google.com'); - promise = driver.getAllWindowHandles(); - promise = driver.getCapabilities(); - promise = driver.getCurrentUrl(); - promise = driver.getPageSource() - promise = driver.getSession(); - promise = driver.getTitle(); - promise = driver.getWindowHandle(); + voidPromise = driver.get('http://www.google.com'); + driver.getAllWindowHandles().then(function (handles: string[]) { }); + driver.getCapabilities().then(function (caps: webdriver.Capabilities) { }); + stringPromise = driver.getCurrentUrl(); + stringPromise = driver.getPageSource() + driver.getSession().then(function (session: webdriver.Session) { });; + stringPromise = driver.getTitle(); + stringPromise = driver.getWindowHandle(); - promise = driver.isElementPresent(webdriver.By.className('ABC')); - promise = driver.isElementPresent({className: 'ABC'}); - promise = driver.isElementPresent(webdriver.By.js('function(){}'), 1, 2, 3); - promise = driver.isElementPresent({js: 'function(){}'}, 1, 2, 3); + booleanPromise = driver.isElementPresent(webdriver.By.className('ABC')); + booleanPromise = driver.isElementPresent({className: 'ABC'}); + booleanPromise = driver.isElementPresent(webdriver.By.js('function(){}'), 1, 2, 3); + booleanPromise = driver.isElementPresent({js: 'function(){}'}, 1, 2, 3); var options: webdriver.WebDriverOptions = driver.manage(); var navigation: webdriver.WebDriverNavigation = driver.navigate(); var locator: webdriver.WebDriverTargetLocator = driver.switchTo(); - promise = driver.quit(); - promise = driver.schedule(new webdriver.Command(webdriver.CommandName.CLICK), 'ABC'); - promise = driver.sleep(123); - promise = driver.takeScreenshot(); + voidPromise = driver.quit(); + voidPromise = driver.schedule(new webdriver.Command(webdriver.CommandName.CLICK), 'ABC'); + voidPromise = driver.sleep(123); + stringPromise = driver.takeScreenshot(); - promise = driver.wait(function() { return true; }, 123); - promise = driver.wait(function() { return true; }, 123, 'Message'); - promise = driver.wait(function() { return promise; }, 123); - promise = driver.wait(function() { return promise; }, 123, 'Message'); + booleanPromise = driver.wait(function() { return true; }, 123); + booleanPromise = driver.wait(function() { return true; }, 123, 'Message'); driver = webdriver.WebDriver.attachToSession(executor, 'ABC'); driver = webdriver.WebDriver.createSession(executor, webdriver.Capabilities.android()); @@ -606,55 +721,75 @@ function TestWebElement() { build(); var element: webdriver.WebElement; - var promise: webdriver.promise.Promise = new webdriver.promise.Promise(); - element = new webdriver.WebElement(driver, 'ID'); - element = new webdriver.WebElement(driver, promise); + element = new webdriver.WebElement(driver, { ELEMENT: 'ID' }); + element = new webdriver.WebElement(driver, new webdriver.promise.Promise()); - var deferred: webdriver.promise.Deferred = element; + var voidPromise: webdriver.promise.Promise; + var stringPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; - promise = element.clear(); - promise = element.click(); + voidPromise = element.clear(); + voidPromise = element.click(); element = element.findElement(webdriver.By.id('ABC')); element = element.findElement({id: 'ABC'}); - element = element.findElement(webdriver.By.js('function(){}'), 1, 2, 3); - element = element.findElement({js: 'function(){}'}, 1, 2, 3); - promise = element.findElements(webdriver.By.className('ABC')); - promise = element.findElements({className: 'ABC'}); - promise = element.findElements(webdriver.By.js('function(){}'), 1, 2, 3); - promise = element.findElements({js: 'function(){}'}, 1, 2, 3); + element.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); + element.findElements({ className: 'ABC' }).then(function (elements: webdriver.WebElement[]) { }); - promise = element.isElementPresent(webdriver.By.className('ABC')); - promise = element.isElementPresent({className: 'ABC'}); - promise = element.isElementPresent(webdriver.By.js('function(){}'), 1, 2, 3); - promise = element.isElementPresent({js: 'function(){}'}, 1, 2, 3); + booleanPromise = element.isElementPresent(webdriver.By.className('ABC')); + booleanPromise = element.isElementPresent({className: 'ABC'}); - promise = element.getAttribute('class'); - promise = element.getCssValue('display'); + stringPromise = element.getAttribute('class'); + stringPromise = element.getCssValue('display'); driver = element.getDriver(); - promise = element.getInnerHtml(); - promise = element.getLocation(); - promise = element.getOuterHtml(); - promise = element.getSize(); - promise = element.getTagName(); - promise = element.getText(); - promise = element.isDisplayed(); - promise = element.isEnabled(); - promise = element.isSelected(); - promise = element.sendKeys('A', 'B', 'C'); - promise = element.submit(); - promise = element.toWireValue(); + stringPromise = element.getInnerHtml(); + element.getLocation().then(function (location: webdriver.ILocation) { }); + stringPromise = element.getOuterHtml(); + element.getSize().then(function (size: webdriver.ISize) { }); + stringPromise = element.getTagName(); + stringPromise = element.getText(); + booleanPromise = element.isDisplayed(); + booleanPromise = element.isEnabled(); + booleanPromise = element.isSelected(); + voidPromise = element.sendKeys('A', 'B', 'C'); + voidPromise = element.submit(); + element.getId().then(function (id: webdriver.IWebElementId) { }); - promise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, 'ID2')); + booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, { ELEMENT: 'ID2' })); var key: string = webdriver.WebElement.ELEMENT_KEY; } +function TestWebElementPromise() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var elementPromise: webdriver.WebElementPromise = driver.findElement(webdriver.By.id('id')); + + elementPromise.cancel(); + elementPromise.cancel('reason'); + + var bool: boolean = elementPromise.isPending(); + + elementPromise.then(); + elementPromise.then(function (element: webdriver.WebElement) { }); + elementPromise.then(function (element: webdriver.WebElement) { }, function (error: any) { }); + elementPromise.then(function (element: webdriver.WebElement) { }, function (error: any) { }).then(function (result: string) { }); + + elementPromise.thenCatch(function (error: any) { }).then(function (value: any) { }); + + elementPromise.thenFinally(function () { }); +} + function TestLogging() { - webdriver.logging.Preferences['name'] = 'ABC'; - var level: webdriver.logging.Level = webdriver.logging.getLevel('OFF'); + var preferences: webdriver.logging.Preferences = new webdriver.logging.Preferences(); + preferences.setLevel(webdriver.logging.Type.BROWSER, webdriver.logging.Level.ALL); + var prefs: any = preferences.toJSON(); + + var level: webdriver.logging.ILevel = webdriver.logging.getLevel('OFF'); level = webdriver.logging.getLevel(1); level = webdriver.logging.Level.ALL; @@ -667,13 +802,6 @@ function TestLogging() { var name: string = level.name; var value: number = level.value; - name = webdriver.logging.LevelName.ALL; - name = webdriver.logging.LevelName.DEBUG; - name = webdriver.logging.LevelName.INFO; - name = webdriver.logging.LevelName.OFF; - name = webdriver.logging.LevelName.SEVERE; - name = webdriver.logging.LevelName.WARNING; - var type: string; type = webdriver.logging.Type.BROWSER; type = webdriver.logging.Type.CLIENT; @@ -702,47 +830,132 @@ function TestLoggingEntry() { entry = webdriver.logging.Entry.fromClosureLogRecord({}, webdriver.logging.Type.DRIVER); } -function TestProcess() { - var isNative: boolean = webdriver.process.isNative(); - var value: string; +function TestPromiseModule() { + var cancellationError: webdriver.promise.CancellationError = new webdriver.promise.CancellationError(); + cancellationError = new webdriver.promise.CancellationError("message"); + var str: string = cancellationError.message; + str = cancellationError.name; - value = webdriver.process.getEnv('name'); - value = webdriver.process.getEnv('name', 'default'); + var stringPromise: webdriver.promise.Promise = new webdriver.promise.Promise(); + var numberPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; + var voidPromise: webdriver.promise.Promise; - webdriver.process.setEnv('name', 'value'); - webdriver.process.setEnv('name', 123); -} + webdriver.promise.all([new webdriver.promise.Promise()]).then(function (values: string[]) { }); -function TestPromise() { - var promise: webdriver.promise.Promise = new webdriver.promise.Promise(); + webdriver.promise.asap('abc', function(value: any){ return true; }); + webdriver.promise.asap('abc', function(value: any){}, function(err: any) { return 'ABC'; }); - webdriver.promise.asap(promise, function(value: any){ return true; }); - webdriver.promise.asap(promise, function(value: any){}, function(err: any) { return 'ABC'; }); + stringPromise = webdriver.promise.checkedNodeCall(function(err: any, value: any) { return 'abc'; }); - promise = webdriver.promise.checkedNodeCall(function(err: any, value: any) { return 123; }); + webdriver.promise.consume(function () { + return 5; + }).then(function (value: number) { }); + webdriver.promise.consume(function () { + return 5; + }, this).then(function (value: number) { }); + webdriver.promise.consume(function (a: number, b: number, c: number) { + 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[]) { + return true; + }); + numbersPromise = webdriver.promise.filter([1, 2, 3], function (el: number, index: number, arr: number[]) { + return true; + }, this); + numbersPromise = webdriver.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { + return true; + }); + numbersPromise = webdriver.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { + return true; + }, this); + + numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, index: number, arr: number[]) { + return true; + }); + numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, index: number, arr: number[]) { + return true; + }, this); + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { + return true; + }); + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { + return true; + }, this); var flow: webdriver.promise.ControlFlow = webdriver.promise.controlFlow(); - promise = webdriver.promise.createFlow(function(newFlow: webdriver.promise.ControlFlow) { }); + stringPromise = webdriver.promise.createFlow(function(newFlow: webdriver.promise.ControlFlow) { return 'ABC' }); - var deferred: webdriver.promise.Deferred; - deferred = webdriver.promise.defer(function() {}); - deferred = webdriver.promise.defer(function(reason?: any) {}); + var deferred: webdriver.promise.Deferred; + deferred = webdriver.promise.defer(); + deferred = webdriver.promise.defer(); - promise = webdriver.promise.delayed(123); + stringPromise = deferred.promise; - promise = webdriver.promise.fulfilled(); - promise = webdriver.promise.fulfilled({a: 123}); + deferred.fulfill('ABC'); + deferred.reject('error'); - promise = webdriver.promise.fullyResolved({a: 123}); + voidPromise = webdriver.promise.delayed(123); + voidPromise = webdriver.promise.fulfilled(); + stringPromise = webdriver.promise.fulfilled('abc'); + + stringPromise = webdriver.promise.fullyResolved('abc'); + + var bool: boolean = webdriver.promise.isGenerator(function () { }); var isPromise: boolean = webdriver.promise.isPromise('ABC'); - promise = webdriver.promise.rejected({a: 123}); + voidPromise = webdriver.promise.rejected({a: 123}); webdriver.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); - promise = webdriver.promise.when(promise, function(value: any) { return 123; }, function(err: Error) { return 123; }); + 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()). + build(); + + var conditionB: webdriver.until.Condition = new webdriver.until.Condition('message', function (driver: webdriver.WebDriver) { return true; }); + var conditionBBase: webdriver.until.Condition = conditionB; + var conditionWebElement: webdriver.until.Condition; + var conditionWebElements: webdriver.until.Condition; + + conditionB = webdriver.until.ableToSwitchToFrame(5); + var conditionAlert: webdriver.until.Condition = webdriver.until.alertIsPresent(); + var el: webdriver.WebElement = driver.findElement(webdriver.By.id('id')); + conditionB = webdriver.until.elementIsDisabled(el); + conditionB = webdriver.until.elementIsEnabled(el); + conditionB = webdriver.until.elementIsNotSelected(el); + conditionB = webdriver.until.elementIsNotVisible(el); + conditionB = webdriver.until.elementIsSelected(el); + conditionB = webdriver.until.elementIsVisible(el); + conditionB = webdriver.until.elementTextContains(el, 'text'); + conditionB = webdriver.until.elementTextIs(el, 'text'); + conditionB = webdriver.until.elementTextMatches(el, /text/); + conditionB = webdriver.until.stalenessOf(el); + conditionB = webdriver.until.titleContains('text'); + conditionB = webdriver.until.titleIs('text'); + conditionB = webdriver.until.titleMatches(/text/); + + conditionWebElement = webdriver.until.elementLocated(webdriver.By.id('id')); + conditionWebElements = webdriver.until.elementsLocated(webdriver.By.className('class')); } function TestControlFlow() { @@ -758,19 +971,20 @@ function TestControlFlow() { var eventType: string; eventType = webdriver.promise.ControlFlow.EventType.IDLE; + eventType = webdriver.promise.ControlFlow.EventType.RESET; eventType = webdriver.promise.ControlFlow.EventType.SCHEDULE_TASK; eventType = webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION; var e: any = flow.annotateError(new Error('Error')); - var promise: webdriver.promise.Promise; + var stringPromise: webdriver.promise.Promise; - promise = flow.await(promise); + stringPromise = flow.await(stringPromise); flow.clearHistory(); - promise = flow.execute(function() { return promise; }); - promise = flow.execute(function() { return promise; }, 'Description'); + stringPromise = flow.execute(function() { return stringPromise; }); + stringPromise = flow.execute(function() { return stringPromise; }, 'Description'); var history: string[] = flow.getHistory(); @@ -778,12 +992,12 @@ function TestControlFlow() { flow.reset(); - promise = flow.timeout(123); - promise = flow.timeout(123, 'Description'); + var voidPromise: webdriver.promise.Promise = flow.timeout(123); + voidPromise = flow.timeout(123, 'Description'); - promise = flow.wait(function() { return true; }, 123); - promise = flow.wait(function() { return true; }, 123, 'Timeout Message'); - promise = flow.wait(function() { return promise; }, 123, 'Timeout Message'); + voidPromise = flow.wait(function() { return true; }, 123); + voidPromise = flow.wait(function() { return true; }, 123, 'Timeout Message'); + voidPromise = flow.wait(function() { return stringPromise; }, 123, 'Timeout Message'); var timer: webdriver.promise.IControlFlowTimer = flow.timer; @@ -792,53 +1006,55 @@ function TestControlFlow() { } function TestDeferred() { - var deferred: webdriver.promise.Deferred; + var deferred: webdriver.promise.Deferred; - deferred = new webdriver.promise.Deferred(); - deferred = new webdriver.promise.Deferred(function() {}); - deferred = new webdriver.promise.Deferred(function(reason: any) { }); - deferred = new webdriver.promise.Deferred(function() {}, new webdriver.promise.ControlFlow()); + deferred = new webdriver.promise.Deferred(); + deferred = new webdriver.promise.Deferred(new webdriver.promise.ControlFlow()); - var promise: webdriver.promise.Promise = deferred; + var promise: webdriver.promise.Promise = deferred.promise; deferred.errback(new Error('Error')); deferred.errback('Error'); - deferred.fulfill(123); + deferred.fulfill('abc'); deferred.reject(new Error('Error')); deferred.reject('Error'); deferred.removeAll(); - - promise = deferred.promise; } function TestPromiseClass() { - var promise: webdriver.promise.Promise = new webdriver.promise.Promise(); + var promise: webdriver.promise.Promise = new webdriver.promise.Promise(); - var obj = { - a: 5 - } - - promise = promise.addBoth(function( a: any ) { }); - promise = promise.addBoth(function( a: any ) { return 123; }); - promise = promise.addBoth(function( a: any ) { }, obj); - - promise = promise.addCallback(function( a: any ) { }); - promise = promise.addCallback(function( a: any ) { return 123; }); - promise = promise.addCallback(function( a: any ) { }, obj); - - promise = promise.addErrback(function( e: any ) { }); - promise = promise.addErrback(function( e: any ) { return 123; }); - promise = promise.addErrback(function( e: any ) { }, obj); - - promise.cancel(obj); + promise.cancel('Abort'); var isPending: boolean = promise.isPending(); promise = promise.then(); - promise = promise.then(function( a: any ) { }); - promise = promise.then(function( a: any ) { return 123; }); - promise = promise.then(function( a: any ) {}, function( e: any) {}); - promise = promise.then(function( a: any ) {}, function( e: any) { return 123; }); + promise = promise.then(function( a: string ) { }); + promise = promise.then(function( a: string ) { return 'cde'; }); + promise = promise.then(function( a: string ) {}, function( e: any) {}); + promise = promise.then(function (a: string) { }, function (e: any) { return 123; }); + + promise = promise.thenCatch(function (error: any) { }); + + promise.thenFinally(function () { }); +} + +function TestThenableClass() { + var thenable: webdriver.promise.Thenable = new webdriver.promise.Thenable(); + + thenable.cancel('Abort'); + + var isPending: boolean = thenable.isPending(); + + thenable = thenable.then(); + thenable = thenable.then(function (a: string) { }); + thenable = thenable.then(function (a: string) { return 'cde'; }); + thenable = thenable.then(function (a: string) { }, function (e: any) { }); + thenable = thenable.then(function (a: string) { }, function (e: any) { return 123; }); + + thenable = thenable.thenCatch(function (error: any) { }); + + thenable.thenFinally(function () { }); } function TestErrorCode() { @@ -914,4 +1130,32 @@ function TestError() { state = webdriver.error.Error.State.UNKNOWN_COMMAND; state = webdriver.error.Error.State.UNKNOWN_ERROR; state = webdriver.error.Error.State.UNSUPPORTED_OPERATION; +} + +function TestTestingModule() { + testing.before(function () { + }); + + testing.beforeEach(function () { + }); + + testing.describe("My test suite", function () { + testing.it("My test", function () { + }); + + testing.iit("My exclusive test.", function () { + }); + + }); + + testing.xdescribe("My disabled suite", function () { + testing.xit("My disabled test.", function () { + }); + }); + + testing.after(function () { + }); + + testing.afterEach(function () { + }); } \ No newline at end of file diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index a4d1017aa5..a1b777d596 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1,699 +1,560 @@ -// Type definitions for Selenium WebDriverJS 2.39.0 +// Type definitions for Selenium WebDriverJS 2.44.0 // Project: https://code.google.com/p/selenium/ // Definitions by: Bill Armstrong // Definitions: https://github.com/borisyankov/DefinitelyTyped +declare module chrome { + /** + * Creates a new WebDriver client for Chrome. + * + * @extends {webdriver.WebDriver} + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(webdriver.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 {webdriver.promise.ControlFlow=} opt_flow The control flow to use, or + * {@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); + } + + interface IOptionsValues { + args: string[]; + binary?: string; + detach: boolean; + extensions: string[]; + localState?: any; + logFile?: string; + prefs?: any; + } + + /** + * Class for managing ChromeDriver specific options. + */ + class Options { + /** + * @constructor + */ + constructor(); + + /** + * Extracts the ChromeDriver specific options from the given capabilities + * object. + * @param {!webdriver.Capabilities} capabilities The capabilities object. + * @return {!Options} The ChromeDriver options. + */ + static fromCapabilities(capabilities: webdriver.Capabilities): Options; + + + /** + * Add additional command line arguments to use when launching the Chrome + * 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: string[]): Options; + + + /** + * Add additional extensions to install when launching Chrome. 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: any[]): Options; + + + /** + * Sets the path to the Chrome binary to use. On Mac OS X, this path should + * reference the actual Chrome executable, not just the application binary + * (e.g. "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"). + * + * The binary path be absolute or relative to the chromedriver server + * executable, but it must exist on the machine that will launch Chrome. + * + * @param {string} path The path to the Chrome binary to use. + * @return {!Options} A self reference. + */ + setChromeBinaryPath(path: string): Options; + + + /** + * Sets whether to leave the started Chrome browser running if the controlling + * ChromeDriver service is killed before {@link webdriver.WebDriver#quit()} is + * called. + * @param {boolean} detach Whether to leave the browser running if the + * chromedriver service is killed before the session. + * @return {!Options} A self reference. + */ + detachDriver(detach: boolean): Options; + + + /** + * Sets the user preferences for Chrome's user profile. See the "Preferences" + * file in Chrome's user data directory for examples. + * @param {!Object} prefs Dictionary of user preferences to use. + * @return {!Options} A self reference. + */ + setUserPreferences(prefs: any): Options; + + + /** + * Sets the logging preferences for the new session. + * @param {!webdriver.logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + + /** + * Sets preferences for the "Local State" file in Chrome's user data + * directory. + * @param {!Object} state Dictionary of local state preferences. + * @return {!Options} A self reference. + */ + setLocalState(state: any): Options; + + + /** + * Sets the path to Chrome's log file. This path should exist on the machine + * that will launch Chrome. + * @param {string} path Path to the log file to use. + * @return {!Options} A self reference. + */ + setChromeLogFile(path: string): Options; + + + /** + * Sets the proxy settings for the new session. + * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + + /** + * Converts this options instance to a {@link webdriver.Capabilities} object. + * @param {webdriver.Capabilities=} opt_capabilities The capabilities to merge + * these options into, if any. + * @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; + } + + /** + * Creates {@link remote.DriverService} instances that manage a ChromeDriver + * server. + */ + class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the chromedriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the chromedriver + * cannot be found on the PATH. + * @constructor + */ + constructor(opt_exe?: string); + + /** + * Sets the port to start the ChromeDriver 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; + + + /** + * Sets the number of threads the driver should use to manage HTTP requests. + * By default, the driver will use 4 threads. + * @param {number} n The number of threads to use. + * @return {!ServiceBuilder} A self reference. + */ + setNumHttpThreads(n: number): ServiceBuilder; + + + /** + * Sets the base path for WebDriver REST commands (e.g. "/wd/hub"). + * By default, the driver will accept commands relative to "/". + * @param {string} path The base path to use. + * @return {!ServiceBuilder} A self reference. + */ + setUrlBasePath(path: string): 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): ServiceBuilder; + setStdio(config: any[]): 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: { [key: string]: string }): 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(): any; + } + + /** + * Returns the default ChromeDriver service. If such a service has not been + * configured, one will be constructed using the default configuration for + * a ChromeDriver executable found on the system PATH. + * @return {!remote.DriverService} The default ChromeDriver service. + */ + function getDefaultService(): any; + + /** + * 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; +} + +declare module 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; + } + + /** + * 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); + } + + /** + * Configuration options for the FirefoxDriver. + */ + 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; + + + /** + * 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 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; + } + + /** + * 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; + } +} + +declare module 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. + */ + function createExecutor(url: string): webdriver.CommandExecutor; + function createExecutor(url: webdriver.promise.Promise): webdriver.CommandExecutor; +} + declare module webdriver { - module logging { - - /** - * A hash describing log preferences. - * @typedef {Object.} - */ - var Preferences: any; - - /** - * Log level names from WebDriver's JSON wire protocol. - * @enum {string} - */ - class LevelName { - static ALL: string; - static DEBUG: string; - static INFO: string; - static WARNING: string; - static SEVERE: string; - static OFF: string; - } - - /** - * Common log types. - * @enum {string} - */ - class Type { - /** Logs originating from the browser. */ - static BROWSER: string; - /** Logs from a WebDriver client. */ - static CLIENT: string; - /** Logs from a WebDriver implementation. */ - static DRIVER: string; - /** Logs related to performance. */ - static PERFORMANCE: string; - /** Logs from the remote server. */ - static SERVER: string; - } - - /** - * Logging levels. - * @enum {{value: number, name: webdriver.logging.LevelName}} - */ - class Level { - //region Static Properties - - static ALL: Level; - static DEBUG: Level; - static INFO: Level; - static WARNING: Level; - static SEVERE: Level; - static OFF: Level; - - //endregion - - //region Properties - - value: number; - name: string; - - //endregion - } - - /** - * Converts a level name or value to a {@link webdriver.logging.Level} value. - * If the name/value is not recognized, {@link webdriver.logging.Level.ALL} - * will be returned. - * @param {(number|string)} nameOrValue The log level name, or value, to - * convert . - * @return {!webdriver.logging.Level} The converted level. - */ - function getLevel(nameOrValue: string): webdriver.logging.Level; - function getLevel(nameOrValue: number): webdriver.logging.Level; - - /** - * A single log entry. - */ - class Entry { - - //region Constructors - - /** - * @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: webdriver.logging.Level, message: string, opt_timestamp?:number, opt_type?:string); - constructor(level: string, message: string, opt_timestamp?:number, opt_type?:string); - - //endregion - - //region Public Properties - - /** @type {!webdriver.logging.Level} */ - level: webdriver.logging.Level; - - /** @type {string} */ - message: string; - - /** @type {number} */ - timestamp: number; - - /** @type {string} */ - type: string; - - //endregion - - //region Static Methods - - /** - * 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): webdriver.logging.Entry; - - //endregion - - //region Methods - - /** - * @return {{level: string, message: string, timestamp: number, - * type: string}} The JSON representation of this entry. - */ - toJSON(): webdriver.logging.Level; - - //endregion - } - } - - module promise { - - //region Functions - - /** - * @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) => any): 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; - - /** - * 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; - - /** - * Creates a new deferred object. - * @param {Function=} opt_canceller Function to call when cancelling the - * computation of this instance's value. - * @return {!webdriver.promise.Deferred} The new deferred object. - */ - function defer(opt_canceller?: any): 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?: 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: (error: any, value: any) => 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: any, opt_callback?: (value: any) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise; - - /** - * Invokes the appropriate callback function as soon as a promised - * {@code value} is resolved. This function is similar to - * {@code 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: (value: any) => any, opt_errback?: (error: any) => any): void; - - /** - * 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; - - //endregion - - /** - * Represents the eventual value of a completed operation. Each promise may be - * in one of three states: pending, resolved, or rejected. Each promise starts - * in the pending state and may make a single transition to either a - * fulfilled or failed state. - * - *

This class is based on the Promise/A proposal from CommonJS. Additional - * functions are provided for API compatibility with Dojo Deferred objects. - * - * @see http://wiki.commonjs.org/wiki/Promises/A - */ - class Promise { - - //region Constructors - - /** - * @constructor - * @see http://wiki.commonjs.org/wiki/Promises/A - */ - constructor(); - - //endregion - - //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(reason: any): 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 {Function=} 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 {Function=} opt_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. - */ - then(opt_callback?: (value: any) => any, opt_errback?: (error: any) => any): Promise; - - /** - * Registers a function to be invoked when this promise is successfully - * resolved. This function is provided for backwards compatibility with the - * Dojo Deferred API. - * - * @param {Function} callback The function to call if this promise is - * successfully resolved. The function should expect a single argument: the - * promise's resolved value. - * @param {!Object=} opt_self The object which |this| should refer to when the - * function is invoked. - * @return {!webdriver.promise.Promise} A new promise which will be resolved - * with the result of the invoked callback. - */ - addCallback(callback: (value: any) => any, opt_self?: any): Promise; - - - /** - * Registers a function to be invoked when this promise is rejected. - * This function is provided for backwards compatibility with the - * Dojo Deferred API. - * - * @param {Function} errback The function to call if this promise is - * rejected. The function should expect a single argument: the rejection - * reason. - * @param {!Object=} opt_self The object which |this| should refer to when the - * function is invoked. - * @return {!webdriver.promise.Promise} A new promise which will be resolved - * with the result of the invoked callback. - */ - addErrback(errback: (error: any) => any, opt_self?: any): Promise; - - /** - * Registers a function to be invoked when this promise is either rejected or - * resolved. This function is provided for backwards compatibility with the - * Dojo Deferred API. - * - * @param {Function} callback The function to call when this promise is - * either resolved or rejected. The function should expect a single - * argument: the resolved value or rejection error. - * @param {!Object=} opt_self The object which |this| should refer to when the - * function is invoked. - * @return {!webdriver.promise.Promise} A new promise which will be resolved - * with the result of the invoked callback. - */ - addBoth(callback : (value: any) => any, opt_self?: any): Promise; - - /** - * An alias for {@code webdriver.promise.Promise.prototype.then} that permits - * the scope of the invoked function to be specified. This function is provided - * for backwards compatibility with the Dojo Deferred API. - * - * @param {Function} callback The function to call if this promise is - * successfully resolved. The function should expect a single argument: the - * promise's resolved value. - * @param {Function} errback The function to call if this promise is - * rejected. The function should expect a single argument: the rejection - * reason. - * @param {!Object=} opt_self The object which |this| should refer to when the - * function is invoked. - * @return {!webdriver.promise.Promise} A new promise which will be resolved - * with the result of the invoked callback. - */ - addCallbacks(callback: (value: any) => any, errback: (error: any) => any, opt_self?: any): Promise; - - //endregion - } - - /** - * Represents a value that will be resolved at some point in the future. This - * class represents the protected "producer" half of a Promise - each Deferred - * has a {@code promise} property that may be returned to consumers for - * registering callbacks, reserving the ability to resolve the deferred to the - * producer. - * - *

If this Deferred is rejected and there are no listeners registered before - * the next turn of the event loop, the rejection will be passed to the - * {@link webdriver.promise.ControlFlow} as an unhandled failure. - * - *

If this Deferred is cancelled, the cancellation reason will be forward to - * the Deferred's canceller function (if provided). The canceller may return a - * truth-y value to override the reason provided for rejection. - * - * @extends {webdriver.promise.Promise} - */ - class Deferred extends Promise { - //region Constructors - - /** - * - * @param {Function=} opt_canceller Function to call when cancelling the - * computation of this instance's value. - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow - * this instance was created under. This should only be provided during - * unit tests. - * @constructor - */ - constructor(opt_canceller?: any, opt_flow?: webdriver.promise.ControlFlow); - - //endregion - - //region Properties - - /** - * The consumer promise for this instance. Provides protected access to the - * callback registering functions. - * @type {!webdriver.promise.Promise} - */ - promise: webdriver.promise.Promise; - - //endregion - - //region Methods - - /** - * Rejects this promise. If the error is itself a promise, this instance will - * be chained to it and be rejected with the error's resolved value. - * @param {*=} opt_error The rejection reason, typically either a - * {@code Error} or a {@code string}. - */ - reject(opt_error?: any): void; - errback(opt_error?: any): void; - - /** - * Resolves this promise with the given value. If the value is itself a - * promise and not a reference to this deferred, this instance will wait for - * it before resolving. - * @param {*=} opt_value The resolved value. - */ - fulfill(opt_value?: any): void; - - /** - * Cancels the computation of this promise's value and flags the promise as a - * rejected value. - * @param {*=} opt_reason The reason for cancelling this promise. - */ - cancel(opt_reason?: any): void; - - /** - * Removes all of the listeners previously registered on this deferred. - * @throws {Error} If this deferred has already been resolved. - */ - removeAll(): void; - - //endregion - } - - interface IControlFlowTimer { - clearInterval: (ms: number) => void; - clearTimeout: (ms: number) => void; - setInterval: (fn: any, ms: number) => number; - setTimeout: (fn: any, ms: number) => number; - } - - /** - * Handles the execution of scheduled tasks, each of which may be an - * asynchronous operation. The control flow will ensure tasks are executed in - * the ordered scheduled, starting each task only once those before it have - * completed. - * - *

Each task scheduled within this flow may return a - * {@link webdriver.promise.Promise} to indicate it is an asynchronous - * operation. The ControlFlow will wait for such promises to be resolved before - * marking the task as completed. - * - *

Tasks and each callback registered on a {@link webdriver.promise.Deferred} - * will be run in their own ControlFlow frame. Any tasks scheduled within a - * frame will have priority over previously scheduled tasks. Furthermore, if - * any of the tasks in the frame fails, the remainder of the tasks in that frame - * will be discarded and the failure will be propagated to the user through the - * callback/task's promised result. - * - *

Each time a ControlFlow empties its task queue, it will fire an - * {@link webdriver.promise.ControlFlow.EventType.IDLE} event. Conversely, - * whenever the flow terminates due to an unhandled error, it will remove all - * remaining tasks in its queue and fire an - * {@link webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION} event. If - * there are no listeners registered with the flow, the error will be - * rethrown to the global error handler. - * - * @extends {webdriver.EventEmitter} - */ - class ControlFlow extends webdriver.EventEmitter { - - //region Constructors - - /** - * @param {webdriver.promise.ControlFlow.Timer=} opt_timer The timer object - * to use. Should only be set for testing. - * @constructor - */ - constructor(opt_timer?: webdriver.promise.IControlFlowTimer); - - //endregion - - //region Properties - - /** - * The timer used by this instance. - * @type {webdriver.promise.ControlFlow.Timer} - */ - timer: webdriver.promise.IControlFlowTimer; - - //endregion - - //region Static Properties - - /** - * The default timer object, which uses the global timer functions. - * @type {webdriver.promise.ControlFlow.Timer} - */ - static defaultTimer: webdriver.promise.IControlFlowTimer; - - /** - * Events that may be emitted by an {@link webdriver.promise.ControlFlow}. - * @enum {string} - */ - static EventType: { - /** Emitted when all tasks have been successfully executed. */ - IDLE: string; - - /** Emitted whenever a new task has been scheduled. */ - SCHEDULE_TASK: string; - - /** - * Emitted whenever a control flow aborts due to an unhandled promise - * rejection. This event will be emitted along with the offending rejection - * reason. Upon emitting this event, the control flow will empty its task - * queue and revert to its initial state. - */ - UNCAUGHT_EXCEPTION: string; - }; - - /** - * How often, in milliseconds, the event loop should run. - * @type {number} - * @const - */ - static EVENT_LOOP_FREQUENCY: number; - - //endregion - - //region Methods - - /** - * Resets this instance, clearing its queue and removing all event listeners. - */ - reset(): void; - - /** - * Returns a summary of the recent task activity for this instance. This - * includes the most recently completed task, as well as any parent tasks. In - * the returned summary, the task at index N is considered a sub-task of the - * task at index N+1. - * @return {!Array.} A summary of this instance's recent task - * activity. - */ - getHistory(): string[]; - - /** Clears this instance's task history. */ - clearHistory(): void; - - /** - * Appends a summary of this instance's recent task history to the given - * error's stack trace. This function will also ensure the error's stack trace - * is in canonical form. - * @param {!(Error|goog.testing.JsUnitException)} e The error to annotate. - * @return {!(Error|goog.testing.JsUnitException)} The annotated error. - */ - annotateError(e: any): any; - - /** - * @return {string} The scheduled tasks still pending with this instance. - */ - getSchedule(): string; - - /** - * Schedules a task for execution. If there is nothing currently in the - * queue, the task will be executed in the next turn of the event loop. - * - * @param {!Function} fn The function to call to start the task. If the - * function returns a {@link webdriver.promise.Promise}, this instance - * will wait for it to be resolved before starting the next task. - * @param {string=} opt_description A description of the task. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * the result of the action. - */ - execute(fn: any, opt_description?: string): webdriver.promise.Promise; - - /** - * Inserts a {@code setTimeout} into the command queue. This is equivalent to - * a thread sleep in a synchronous programming language. - * - * @param {number} ms The timeout delay, in milliseconds. - * @param {string=} opt_description A description to accompany the timeout. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * the result of the action. - */ - timeout(ms: number, opt_description?: string): webdriver.promise.Promise; - - /** - * Schedules a task that shall wait for a condition to hold. Each condition - * function may return any value, but it will always be evaluated as a boolean. - * - *

Condition functions may schedule sub-tasks with this instance, however, - * their execution time will be factored into whether a wait has timed out. - * - *

In the event a condition returns a Promise, the polling loop will wait for - * it to be resolved before evaluating whether the condition has been satisfied. - * The resolution time for a promise is factored into whether a wait has timed - * out. - * - *

If the condition function throws, or returns a rejected promise, the - * wait task will fail. - * - * @param {!Function} condition The condition function to poll. - * @param {number} timeout How long to wait, in milliseconds, for the condition - * to hold before timing out. - * @param {string=} opt_message An optional error message to include if the - * wait times out; defaults to the empty string. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * condition has been satisified. The promise shall be rejected if the wait - * times out waiting for the condition. - */ - wait(condition: any, timeout: number, opt_message?: string): webdriver.promise.Promise; - - /** - * Schedules a task that will wait for another promise to resolve. The resolved - * promise's value will be returned as the task result. - * @param {!webdriver.promise.Promise} promise The promise to wait on. - * @return {!webdriver.promise.Promise} A promise that will resolve when the - * task has completed. - */ - await(promise: webdriver.promise.Promise): webdriver.promise.Promise; - - //endregion - } - } - module error { + interface IErrorCode { + SUCCESS: number; - // NOTE: A class was used instead of an Enum so that it could be extended in Protractor. - class ErrorCode { - static SUCCESS: number; - - static NO_SUCH_ELEMENT: number; - static NO_SUCH_FRAME: number; - static UNKNOWN_COMMAND: number; - static UNSUPPORTED_OPERATION: number; // Alias for UNKNOWN_COMMAND. - static STALE_ELEMENT_REFERENCE: number; - static ELEMENT_NOT_VISIBLE: number; - static INVALID_ELEMENT_STATE: number; - static UNKNOWN_ERROR: number; - static ELEMENT_NOT_SELECTABLE: number; - static JAVASCRIPT_ERROR: number; - static XPATH_LOOKUP_ERROR: number; - static TIMEOUT: number; - static NO_SUCH_WINDOW: number; - static INVALID_COOKIE_DOMAIN: number; - static UNABLE_TO_SET_COOKIE: number; - static MODAL_DIALOG_OPENED: number; - static NO_MODAL_DIALOG_OPEN: number; - static SCRIPT_TIMEOUT: number; - static INVALID_ELEMENT_COORDINATES: number; - static IME_NOT_AVAILABLE: number; - static IME_ENGINE_ACTIVATION_FAILED: number; - static INVALID_SELECTOR_ERROR: number; - static SESSION_NOT_CREATED: number; - static MOVE_TARGET_OUT_OF_BOUNDS: number; - static SQL_DATABASE_ERROR: number; - static INVALID_XPATH_SELECTOR: number; - static INVALID_XPATH_SELECTOR_RETURN_TYPE: number; + 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. - static METHOD_NOT_ALLOWED: number; + METHOD_NOT_ALLOWED: number; } + var ErrorCode: IErrorCode; + /** * Error extension that includes error status codes from the WebDriver wire * protocol: @@ -710,7 +571,7 @@ declare module webdriver { * @param {string=} opt_message Optional error message. * @constructor */ - constructor(code: number, opt_message?: string); + constructor(code: number, opt_message?: string); //endregion @@ -784,124 +645,1327 @@ declare module webdriver { //region Methods /** @return {string} The string representation of this error. */ - toString(): string; + toString(): string; //endregion } } - module process { + module logging { /** - * Queries for a named environment variable. - * @param {string} name The name of the environment variable to look up. - * @param {string=} opt_default The default value if the named variable is not - * defined. - * @return {string} The queried environment variable. + * A hash describing log preferences. + * @typedef {Object.} */ - function getEnv(name: string, opt_default?: string): string; + class Preferences { + setLevel(type: string, level: ILevel): 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; + } /** - * @return {boolean} Whether the current process is Node's native process - * object. + * Common log types. + * @enum {string} */ - function isNative(): boolean; + var Type: IType; /** - * Sets an environment value. If the new value is either null or undefined, the - * environment variable will be cleared. - * @param {string} name The value to set. - * @param {*} value The new value; will be coerced to a string. + * Logging levels. + * @enum {{value: number, name: webdriver.logging.LevelName}} */ - function setEnv(name: string, value: any): void; + interface ILevel { + value: number; + name: string; + } + interface ILevelValues { + ALL: ILevel; + DEBUG: ILevel; + INFO: ILevel; + WARNING: ILevel; + SEVERE: ILevel; + OFF: ILevel; + } + + var Level: ILevelValues; + + /** + * Converts a level name or value to a {@link webdriver.logging.Level} value. + * If the name/value is not recognized, {@link webdriver.logging.Level.ALL} + * will be returned. + * @param {(number|string)} nameOrValue The log level name, or value, to + * convert . + * @return {!webdriver.logging.Level} The converted level. + */ + function getLevel(nameOrValue: string): ILevel; + function getLevel(nameOrValue: number): ILevel; + + interface IEntryJSON { + level: string; + message: string; + timestamp: number; + type: string; + } + + /** + * A single log entry. + */ + class Entry { + + //region Constructors + + /** + * @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); + + //endregion + + //region Public Properties + + /** @type {!webdriver.logging.Level} */ + level: ILevel; + + /** @type {string} */ + message: string; + + /** @type {number} */ + timestamp: number; + + /** @type {string} */ + type: string; + + //endregion + + //region Static Methods + + /** + * 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; + + //endregion + + //region Methods + + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): IEntryJSON; + + //endregion + } } - /** - * Creates new {@code webdriver.WebDriver} clients. Upon instantiation, each - * Builder will configure itself based on the following environment variables: - *

- *
{@code webdriver.AbstractBuilder.SERVER_URL_ENV}
- *
Defines the remote WebDriver server that should be used for command - * command execution; may be overridden using - * {@code webdriver.AbstractBuilder.prototype.usingServer}.
- *
- */ - class AbstractBuilder { - - //region Constructors + module promise { + //region Functions /** - * @constructor + * 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 */ - constructor(); + function all(arr: 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(): 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: ControlFlow) => R): 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): 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): Promise; + function filter(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + + /** + * Creates a new deferred object. + * @return {!webdriver.promise.Deferred} The new deferred object. + */ + function defer(): 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): 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): Promise + function map(arr: Promise, fn: (element: T, index: number, array: T[]) => 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. + */ + 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 + * 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[]): 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[]): 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): Promise; + function when(value: 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 + * 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): 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: ControlFlow): void; //endregion - //region Static Properties - /** - * Environment variable that defines the URL of the WebDriver server that - * should be used for all new WebDriver clients. This setting may be overridden - * using {@code #usingServer(url)}. - * @type {string} - * @const - * @see webdriver.process.getEnv + * Error used when the computation of a promise is cancelled. + * + * @extends {goog.debug.Error} + * @final */ - static SERVER_URL_ENV: string; + class CancellationError { + /** + * @param {string=} opt_msg The cancellation message. + * @constructor + */ + constructor(opt_msg?: string); + name: string; + message: 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. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param {?(function(T): (R|webdriver.promise.Promise.))=} 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 {?(function(*): (R|webdriver.promise.Promise.))=} opt_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 + */ + then(opt_callback?: (value: T) => any, opt_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().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): 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; + } /** - * The default URL of the WebDriver server to use if - * {@link webdriver.AbstractBuilder.SERVER_URL_ENV} is not set. - * @type {string} + * 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. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param {?(function(T): (R|webdriver.promise.Promise.))=} 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 {?(function(*): (R|webdriver.promise.Promise.))=} opt_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 + */ + then(opt_callback?: (value: T) => any, opt_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().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): 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; + + /** + * 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 + * 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}. + * @param {*} object The object to test. + * @return {boolean} Whether the object is an implementation of the Thenable + * interface. + */ + static isImplementation(object: any): boolean; + } + + /** + * Represents the eventual value of a completed operation. Each promise may be + * in one of three states: pending, resolved, or rejected. Each promise starts + * in the pending state and may make a single transition to either a + * fulfilled or failed state. + * + *

This class is based on the Promise/A proposal from CommonJS. Additional + * functions are provided for API compatibility with Dojo Deferred objects. + * + * @see http://wiki.commonjs.org/wiki/Promises/A + */ + class Promise implements IThenable { + + //region Constructors + + /** + * @constructor + * @see http://wiki.commonjs.org/wiki/Promises/A + */ + constructor(); + + //endregion + + //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(reason: any): 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 {Function=} 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 {Function=} opt_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. + */ + then(opt_callback?: (value: T) => any, opt_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().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): 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; + + //endregion + } + + /** + * Represents a value that will be resolved at some point in the future. This + * class represents the protected "producer" half of a Promise - each Deferred + * has a {@code promise} property that may be returned to consumers for + * registering callbacks, reserving the ability to resolve the deferred to the + * producer. + * + *

If this Deferred is rejected and there are no listeners registered before + * the next turn of the event loop, the rejection will be passed to the + * {@link webdriver.promise.ControlFlow} as an unhandled failure. + * + *

If this Deferred is cancelled, the cancellation reason will be forward to + * the Deferred's canceller function (if provided). The canceller may return a + * truth-y value to override the reason provided for rejection. + * + * @extends {webdriver.promise.Promise} + */ + class Deferred extends Promise { + //region Constructors + + /** + * + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow + * this instance was created under. This should only be provided during + * unit tests. + * @constructor + */ + constructor(opt_flow?: ControlFlow); + + //endregion + + static State_: { + BLOCKED: number; + PENDING: number; + REJECTED: number; + RESOLVED: number; + } + + //region Properties + + /** + * The consumer promise for this instance. Provides protected access to the + * callback registering functions. + * @type {!webdriver.promise.Promise} + */ + promise: Promise; + + //endregion + + //region Methods + + /** + * Rejects this promise. If the error is itself a promise, this instance will + * be chained to it and be rejected with the error's resolved value. + * @param {*=} opt_error The rejection reason, typically either a + * {@code Error} or a {@code string}. + */ + reject(opt_error?: any): void; + errback(opt_error?: any): void; + + /** + * Resolves this promise with the given value. If the value is itself a + * promise and not a reference to this deferred, this instance will wait for + * it before resolving. + * @param {*=} opt_value The resolved value. + */ + fulfill(opt_value?: T): void; + + /** + * Removes all of the listeners previously registered on this deferred. + * @throws {Error} If this deferred has already been resolved. + */ + removeAll(): void; + + //endregion + } + + interface IControlFlowTimer { + clearInterval: (ms: number) => void; + clearTimeout: (ms: number) => void; + setInterval: (fn: Function, ms: number) => number; + setTimeout: (fn: Function, ms: number) => number; + } + + /** + * Handles the execution of scheduled tasks, each of which may be an + * asynchronous operation. The control flow will ensure tasks are executed in + * the ordered scheduled, starting each task only once those before it have + * completed. + * + *

Each task scheduled within this flow may return a + * {@link webdriver.promise.Promise} to indicate it is an asynchronous + * operation. The ControlFlow will wait for such promises to be resolved before + * marking the task as completed. + * + *

Tasks and each callback registered on a {@link webdriver.promise.Deferred} + * will be run in their own ControlFlow frame. Any tasks scheduled within a + * frame will have priority over previously scheduled tasks. Furthermore, if + * any of the tasks in the frame fails, the remainder of the tasks in that frame + * will be discarded and the failure will be propagated to the user through the + * callback/task's promised result. + * + *

Each time a ControlFlow empties its task queue, it will fire an + * {@link webdriver.promise.ControlFlow.EventType.IDLE} event. Conversely, + * whenever the flow terminates due to an unhandled error, it will remove all + * remaining tasks in its queue and fire an + * {@link webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION} event. If + * there are no listeners registered with the flow, the error will be + * rethrown to the global error handler. + * + * @extends {webdriver.EventEmitter} + */ + class ControlFlow extends EventEmitter { + + //region Constructors + + /** + * @param {webdriver.promise.ControlFlow.Timer=} opt_timer The timer object + * to use. Should only be set for testing. + * @constructor + */ + constructor(opt_timer?: IControlFlowTimer); + + //endregion + + //region Properties + + /** + * The timer used by this instance. + * @type {webdriver.promise.ControlFlow.Timer} + */ + timer: IControlFlowTimer; + + //endregion + + //region Static Properties + + /** + * The default timer object, which uses the global timer functions. + * @type {webdriver.promise.ControlFlow.Timer} + */ + static defaultTimer: IControlFlowTimer; + + /** + * Events that may be emitted by an {@link webdriver.promise.ControlFlow}. + * @enum {string} + */ + static EventType: { + /** Emitted when all tasks have been successfully executed. */ + IDLE: string; + + /** Emitted when a ControlFlow has been reset. */ + RESET: string; + + /** Emitted whenever a new task has been scheduled. */ + SCHEDULE_TASK: string; + + /** + * Emitted whenever a control flow aborts due to an unhandled promise + * rejection. This event will be emitted along with the offending rejection + * reason. Upon emitting this event, the control flow will empty its task + * queue and revert to its initial state. + */ + UNCAUGHT_EXCEPTION: string; + }; + + /** + * How often, in milliseconds, the event loop should run. + * @type {number} + * @const + */ + static EVENT_LOOP_FREQUENCY: number; + + //endregion + + //region Methods + + /** + * Resets this instance, clearing its queue and removing all event listeners. + */ + reset(): void; + + /** + * Returns a summary of the recent task activity for this instance. This + * includes the most recently completed task, as well as any parent tasks. In + * the returned summary, the task at index N is considered a sub-task of the + * task at index N+1. + * @return {!Array.} A summary of this instance's recent task + * activity. + */ + getHistory(): string[]; + + /** Clears this instance's task history. */ + clearHistory(): void; + + /** + * Appends a summary of this instance's recent task history to the given + * error's stack trace. This function will also ensure the error's stack trace + * is in canonical form. + * @param {!(Error|goog.testing.JsUnitException)} e The error to annotate. + * @return {!(Error|goog.testing.JsUnitException)} The annotated error. + */ + annotateError(e: any): any; + + /** + * @return {string} The scheduled tasks still pending with this instance. + */ + getSchedule(): string; + + /** + * Schedules a task for execution. If there is nothing currently in the + * queue, the task will be executed in the next turn of the event loop. + * + * @param {!Function} fn The function to call to start the task. If the + * function returns a {@link webdriver.promise.Promise}, this instance + * will wait for it to be resolved before starting the next task. + * @param {string=} opt_description A description of the task. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the result of the action. + */ + execute(fn: Function, opt_description?: string): Promise; + + /** + * Inserts a {@code setTimeout} into the command queue. This is equivalent to + * a thread sleep in a synchronous programming language. + * + * @param {number} ms The timeout delay, in milliseconds. + * @param {string=} opt_description A description to accompany the timeout. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the result of the action. + */ + timeout(ms: number, opt_description?: string): Promise; + + /** + * Schedules a task that shall wait for a condition to hold. Each condition + * function may return any value, but it will always be evaluated as a boolean. + * + *

Condition functions may schedule sub-tasks with this instance, however, + * their execution time will be factored into whether a wait has timed out. + * + *

In the event a condition returns a Promise, the polling loop will wait for + * it to be resolved before evaluating whether the condition has been satisfied. + * The resolution time for a promise is factored into whether a wait has timed + * out. + * + *

If the condition function throws, or returns a rejected promise, the + * wait task will fail. + * + * @param {!Function} condition The condition function to poll. + * @param {number} timeout How long to wait, in milliseconds, for the condition + * to hold before timing out. + * @param {string=} opt_message An optional error message to include if the + * wait times out; defaults to the empty string. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * condition has been satisified. The promise shall be rejected if the wait + * times out waiting for the condition. + */ + wait(condition: Function, timeout: number, opt_message?: string): Promise; + + /** + * Schedules a task that will wait for another promise to resolve. The resolved + * promise's value will be returned as the task result. + * @param {!webdriver.promise.Promise} promise The promise to wait on. + * @return {!webdriver.promise.Promise} A promise that will resolve when the + * task has completed. + */ + await(promise: Promise): Promise; + + //endregion + } + } + + module 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 */ - static DEFAULT_SERVER_URL: string; - - //endregion - - //region Methods + var BROWSER_SUPPORTED: boolean; + } + module until { /** - * Configures which WebDriver server should be used for new sessions. Overrides - * the value loaded from the {@link webdriver.AbstractBuilder.SERVER_URL_ENV} - * upon creation of this instance. - * @param {string} url URL of the server to use. - * @return {!webdriver.AbstractBuilder} This Builder instance for chain calling. + * Defines a condition to */ - usingServer(url: string): AbstractBuilder; + class Condition { + /** + * @param {string} message A descriptive error message. Should complete the + * sentence "Waiting [...]" + * @param {function(!webdriver.WebDriver): OUT} fn The condition function to + * evaluate on each iteration of the wait loop. + * @constructor + */ + constructor(message: string, fn: (webdriver: WebDriver) => any); + + /** @return {string} A description of this condition. */ + description(): string; + + /** @type {function(!webdriver.WebDriver): OUT} */ + fn(webdriver: WebDriver): any; + } /** - * @return {string} The URL of the WebDriver server this instance is configured + * 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): Condition; + function ableToSwitchToFrame(frame: IWebElement): Condition; + function ableToSwitchToFrame(frame: Locator): Condition; + function ableToSwitchToFrame(frame: (webdriver: WebDriver) => IWebElement): Condition; + function ableToSwitchToFrame(frame: any): 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(): 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: IWebElement): 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: IWebElement): 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: IWebElement): 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: IWebElement): 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: IWebElement): 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: IWebElement): 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. */ - getServerUrl(): string; + function elementLocated(locator: Locator): Condition; + function elementLocated(locator: any): Condition; /** - * Sets the desired capabilities when requesting a new session. This will - * overwrite any previously set desired capabilities. - * @param {!(Object|webdriver.Capabilities)} capabilities The desired - * capabilities for a new session. - * @return {!webdriver.AbstractBuilder} This Builder instance for chain calling. + * 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 */ - withCapabilities(capabilities: webdriver.Capabilities): AbstractBuilder; - withCapabilities(capabilities: any): AbstractBuilder; + function elementTextContains(element: IWebElement, substr: string): Condition; /** - * @return {!webdriver.Capabilities} The current desired capabilities for this - * builder. + * 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 */ - getCapabilities(): webdriver.Capabilities; + function elementTextIs(element: IWebElement, text: string): Condition; /** - * Builds a new {@link webdriver.WebDriver} instance using this builder's - * current configuration. - * @return {!webdriver.WebDriver} A new WebDriver client. + * 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 */ - build(): webdriver.WebDriver; + function elementTextMatches(element: IWebElement, regex: RegExp): Condition; - //endregion + /** + * 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: Locator): Condition; + function elementsLocated(locator: any): 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: IWebElement): 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): 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): 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): Condition; } interface ILocation { @@ -909,89 +1973,95 @@ declare module webdriver { y: number; } + interface ISize { + width: number; + height: number; + } + /** * 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} */ - class Button { - static LEFT: number; - static MIDDLE: number; - static RIGHT: number; + interface IButton { + LEFT: number; + MIDDLE: number; + RIGHT: number; } + 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 * http://www.google.com.au/search?&q=unicode+pua&btnG=Search - * NOTE: A class was used instead of an Enum so that it could be extended in Protractor * * @enum {string} */ - class Key { - static NULL: string; - static CANCEL: string; // ^break - static HELP: string; - static BACK_SPACE: string; - static TAB: string; - static CLEAR: string; - static RETURN: string; - static ENTER: string; - static SHIFT: string; - static CONTROL: string; - static ALT: string; - static PAUSE: string; - static ESCAPE: string; - static SPACE: string; - static PAGE_UP: string; - static PAGE_DOWN: string; - static END: string; - static HOME: string; - static ARROW_LEFT: string; - static LEFT: string; - static ARROW_UP: string; - static UP: string; - static ARROW_RIGHT: string; - static RIGHT: string; - static ARROW_DOWN: string; - static DOWN: string; - static INSERT: string; - static DELETE: string; - static SEMICOLON: string; - static EQUALS: 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; - static NUMPAD0: string; // number pad keys - static NUMPAD1: string; - static NUMPAD2: string; - static NUMPAD3: string; - static NUMPAD4: string; - static NUMPAD5: string; - static NUMPAD6: string; - static NUMPAD7: string; - static NUMPAD8: string; - static NUMPAD9: string; - static MULTIPLY: string; - static ADD: string; - static SEPARATOR: string; - static SUBTRACT: string; - static DECIMAL: string; - static DIVIDE: string; + 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; - static F1: string; // function keys - static F2: string; - static F3: string; - static F4: string; - static F5: string; - static F6: string; - static F7: string; - static F8: string; - static F9: string; - static F10: string; - static F11: string; - static F12: string; + 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; - static COMMAND: string; // Apple command key - static META: string; // alias for Windows key + COMMAND: string; // Apple command key + META: string; // alias for Windows key /** * Simulate pressing many keys at once in a "chord". Takes a sequence of @@ -1006,9 +2076,11 @@ declare module webdriver { * @return {string} The null-terminated key sequence. * @see http://code.google.com/p/webdriver/issues/detail?id=79 */ - static chord(...var_args: string[]): string; + 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. @@ -1032,7 +2104,7 @@ declare module webdriver { * @param {!webdriver.WebDriver} driver The driver instance to use. * @constructor */ - constructor(driver: webdriver.WebDriver); + constructor(driver: WebDriver); //endregion @@ -1043,7 +2115,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved once * this sequence has completed. */ - perform(): webdriver.promise.Promise; + perform(): webdriver.promise.Promise; /** * Moves the mouse. The location to move to may be specified in terms of the @@ -1055,8 +2127,8 @@ declare module webdriver { * Defaults to (0, 0). * @return {!webdriver.ActionSequence} A self reference. */ - mouseMove(location: webdriver.WebElement, opt_offset?: ILocation): ActionSequence - mouseMove(location: ILocation): ActionSequence + mouseMove(location: IWebElement, opt_offset?: ILocation): ActionSequence; + mouseMove(location: ILocation): ActionSequence; /** * Presses a mouse button. The mouse button will not be released until @@ -1080,7 +2152,7 @@ declare module webdriver { * first argument. * @return {!webdriver.ActionSequence} A self reference. */ - mouseDown(opt_elementOrButton?: webdriver.WebElement, opt_button?: number): ActionSequence; + mouseDown(opt_elementOrButton?: IWebElement, opt_button?: number): ActionSequence; mouseDown(opt_elementOrButton?: number): ActionSequence; /** @@ -1103,7 +2175,7 @@ declare module webdriver { * first argument. * @return {!webdriver.ActionSequence} A self reference. */ - mouseUp(opt_elementOrButton?: webdriver.WebElement, opt_button?: number): ActionSequence; + mouseUp(opt_elementOrButton?: IWebElement, opt_button?: number): ActionSequence; mouseUp(opt_elementOrButton?: number): ActionSequence; /** @@ -1115,8 +2187,8 @@ declare module webdriver { * location to drag to, either as another WebElement or an offset in pixels. * @return {!webdriver.ActionSequence} A self reference. */ - dragAndDrop(element: webdriver.WebElement, location: webdriver.WebElement): ActionSequence; - dragAndDrop(element: webdriver.WebElement, location: ILocation): ActionSequence; + dragAndDrop(element: IWebElement, location: IWebElement): ActionSequence; + dragAndDrop(element: IWebElement, location: ILocation): ActionSequence; /** * Clicks a mouse button. @@ -1134,7 +2206,7 @@ declare module webdriver { * first argument. * @return {!webdriver.ActionSequence} A self reference. */ - click(opt_elementOrButton?: webdriver.WebElement, opt_button?: number): ActionSequence; + click(opt_elementOrButton?: IWebElement, opt_button?: number): ActionSequence; click(opt_elementOrButton?: number): ActionSequence; /** @@ -1156,7 +2228,7 @@ declare module webdriver { * first argument. * @return {!webdriver.ActionSequence} A self reference. */ - doubleClick(opt_elementOrButton?: webdriver.WebElement, opt_button?: number): ActionSequence; + doubleClick(opt_elementOrButton?: IWebElement, opt_button?: number): ActionSequence; doubleClick(opt_elementOrButton?: number): ActionSequence; /** @@ -1199,24 +2271,8 @@ declare module webdriver { * {@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}). - * @extends {webdriver.promise.Deferred} */ - class Alert extends webdriver.promise.Deferred { - - //region Constructors - - /** - * @param {!webdriver.WebDriver} driver The driver controlling the browser this - * alert is attached to. - * @param {!(string|webdriver.promise.Promise)} text Either the message text - * displayed with this alert, or a promise that will be resolved to said - * text. - * @constructor - */ - constructor(driver: webdriver.WebDriver, text: string); - constructor(driver: webdriver.WebDriver, text: webdriver.promise.Promise); - - //endregion + interface Alert { //region Methods @@ -1226,21 +2282,21 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved to the * text displayed with this alert. */ - getText(): webdriver.promise.Promise; + getText(): webdriver.promise.Promise; /** * Accepts this alert. * @return {!webdriver.promise.Promise} A promise that will be resolved when * this command has completed. */ - accept(): webdriver.promise.Promise; + accept(): webdriver.promise.Promise; /** * Dismisses this alert. * @return {!webdriver.promise.Promise} A promise that will be resolved when * this command has completed. */ - dismiss(): webdriver.promise.Promise; + dismiss(): webdriver.promise.Promise; /** * Sets the response text on this alert. This command will return an error if @@ -1250,35 +2306,56 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved when * this command has completed. */ - sendKeys(text: string): webdriver.promise.Promise; + sendKeys(text: string): webdriver.promise.Promise; //endregion } + /** + * AlertPromise is a promise that will be fulfilled with an Alert. This promise + * 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.} + * @final + */ + interface AlertPromise extends Alert, webdriver.promise.IThenable { + } + /** * An error returned to indicate that there is an unhandled modal dialog on the * current page. * @extends {bot.Error} */ - class UnhandledAlertError extends webdriver.error.Error { - //region Constructors - - /** - * @param {string} message The error message. - * @param {!webdriver.Alert} alert The alert handle. - * @constructor - */ - constructor(message: string, alert: webdriver.Alert); - - //endregion - + interface UnhandledAlertError extends webdriver.error.Error { //region Methods /** - * @return {!webdriver.Alert} The open alert. + * @return {string} The text displayed with the unhandled alert. */ - getAlert(): webdriver.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 } @@ -1287,23 +2364,31 @@ declare module webdriver { * Recognized browser names. * @enum {string} */ - class Browser { - static ANDROID: string; - static CHROME: string; - static FIREFOX: string; - static INTERNET_EXPLORER: string; - static IPAD: string; - static IPHONE: string; - static OPERA: string; - static PHANTOM_JS: string; - static SAFARI: string; - static HTMLUNIT: string; + interface IBrowser { + ANDROID: string; + CHROME: string; + FIREFOX: string; + INTERNET_EXPLORER: string; + IPAD: string; + IPHONE: string; + OPERA: string; + PHANTOM_JS: string; + SAFARI: string; + HTMLUNIT: string; } - /** - * @extends {webdriver.AbstractBuilder} - */ - class Builder extends AbstractBuilder { + var Browser: IBrowser + + interface ProxyConfig { + proxyType: string; + proxyAutoconfigUrl?: string; + ftpProxy?: string; + httpProxy?: string; + sslProxy?: string; + noProxy?: string; + } + + class Builder { //region Constructors @@ -1314,43 +2399,146 @@ declare module webdriver { //endregion - //region Static Properties - - /** - * Environment variable that defines the session ID of an existing WebDriver - * session to use when creating clients. If set, all new Builder instances will - * default to creating clients that use this session. To create a new session, - * use {@code #useExistingSession(boolean)}. The use of this environment - * variable requires that {@link webdriver.AbstractBuilder.SERVER_URL_ENV} also - * be set. - * @type {string} - * @const - * @see webdriver.process.getEnv - */ - static SESSION_ID_ENV: string; - - //endregion - //region Methods /** - * Configures the builder to create a client that will use an existing WebDriver - * session. - * @param {string} id The existing session ID to use. - * @return {!webdriver.AbstractBuilder} This Builder instance for chain calling. + * Creates a new WebDriver client based on this builder's current + * configuration. + * + * @return {!webdriver.WebDriver} A new WebDriver instance. + * @throws {Error} If the current configuration is invalid. */ - usingSession(id: string): webdriver.AbstractBuilder; + build(): WebDriver; /** - * @return {string} The ID of the session, if any, this builder is configured - * to reuse. + * Configures the target browser for clients created by this instance. + * Any calls to {@link #withCapabilities} after this function will + * overwrite these settings. + * + *

You may also define the target browser using the {@code SELENIUM_BROWSER} + * environment variable. If set, this environment variable should be of the + * form {@code browser[:[version][:platform]]}. + * + * @param {(string|webdriver.Browser)} name The name of the target browser; + * common defaults are available on the {@link webdriver.Browser} enum. + * @param {string=} opt_version A desired version; may be omitted if any + * version should be used. + * @param {string=} opt_platform The desired platform; may be omitted if any + * version may be used. + * @return {!Builder} A self reference. */ - getSession(): string; + forBrowser(name: string, opt_version?: string, opt_platform?: string): Builder; /** - * @override + * Returns the base set of capabilities this instance is currently configured + * to use. + * @return {!webdriver.Capabilities} The current capabilities for this builder. */ - build(): webdriver.WebDriver; + getCapabilities(): Capabilities; + + /** + * @return {string} The URL of the WebDriver server this instance is configured + * to use. + */ + getServerUrl(): string; + + /** + * Sets the default action to take with an unexpected alert before returning + * an error. + * @param {string} beahvior The desired behavior; should be "accept", "dismiss", + * or "ignore". Defaults to "dismiss". + * @return {!Builder} A self reference. + */ + setAlertBehavior(behavior: string): Builder; + + /** + * Sets Chrome-specific 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 {!chrome.Options} options The ChromeDriver options to use. + * @return {!Builder} A self reference. + */ + setChromeOptions(options: chrome.Options): Builder; + + /** + * Sets the control flow that created drivers should execute actions in. If + * the flow is never set, or is set to {@code null}, it will use the active + * flow at the time {@link #build()} is called. + * @param {webdriver.promise.ControlFlow} flow The control flow to use, or + * {@code null} to + * @return {!Builder} A self reference. + */ + setControlFlow(flow: webdriver.promise.ControlFlow): Builder; + + /** + * Sets whether native events should be used. + * @param {boolean} enabled Whether to enable native events. + * @return {!Builder} A self reference. + */ + setEnableNativeEvents(enabled: boolean): Builder; + + /** + * Sets Firefox-specific 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 {!firefox.Options} options The FirefoxDriver options to use. + * @return {!Builder} A self reference. + */ + setFirefoxOptions(options: firefox.Options): Builder; + + /** + * Sets the logging preferences for the created session. Preferences may be + * changed by repeated calls, or by calling {@link #withCapabilities}. + * @param {!(webdriver.logging.Preferences|Object.)} prefs The + * desired logging preferences. + * @return {!Builder} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Builder; + setLoggingPrefs(prefs: { [key: string]: string }): 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. + * @return {!Builder} A self reference. + */ + setProxy(config: ProxyConfig): Builder; + + /** + * Sets how elements should be scrolled into view for interaction. + * @param {number} behavior The desired scroll behavior: either 0 to align with + * the top of the viewport or 1 to align with the bottom. + * @return {!Builder} A self reference. + */ + setScrollBehavior(behavior: number): Builder; + + /** + * Sets the URL of a remote WebDriver server to use. Once a remote URL has been + * specified, the builder direct all new clients to that server. If this method + * is never called, the Builder will attempt to create all clients locally. + * + *

As an alternative to this method, you may also set the + * {@code SELENIUM_REMOTE_URL} environment variable. + * + * @param {string} url The URL of a remote server to use. + * @return {!Builder} A self reference. + */ + usingServer(url: string): Builder; + + /** + * Sets the desired capabilities when requesting a new session. This will + * overwrite any previously set capabilities. + * @param {!(Object|webdriver.Capabilities)} capabilities The desired + * capabilities for a new session. + * @return {!Builder} A self reference. + */ + withCapabilities(capabilities: Capabilities): Builder; + withCapabilities(capabilities: any): Builder; //endregion } @@ -1359,7 +2547,7 @@ declare module webdriver { * Common webdriver capability keys. * @enum {string} */ - class Capability { + interface ICapability { /** * Indicates whether a driver should accept all SSL certs by default. This @@ -1367,26 +2555,39 @@ declare module webdriver { * a driver can handle insecure SSL certs, see * {@link webdriver.Capability.SECURE_SSL}. */ - static ACCEPT_SSL_CERTS: string; + ACCEPT_SSL_CERTS: string; /** * The browser name. Common browser names are defined in the * {@link webdriver.Browser} enum. */ - static BROWSER_NAME: string; + BROWSER_NAME: string; + + /** + * Defines how elements should be scrolled into the viewport for interaction. + * This capability will be set to zero (0) if elements are aligned with the + * top of the viewport, or one (1) if aligned with the bottom. The default + * behavior is to align with the top of the viewport. + */ + ELEMENT_SCROLL_BEHAVIOR: string; /** * Whether the driver is capable of handling modal alerts (e.g. alert, * confirm, prompt). To define how a driver should handle alerts, * use {@link webdriver.Capability.UNEXPECTED_ALERT_BEHAVIOR}. */ - static HANDLES_ALERTS: string; + HANDLES_ALERTS: string; /** * Key for the logging driver logging preferences. */ - static LOGGING_PREFS: string; + LOGGING_PREFS: string; + + /** + * Whether this session generates native events when simulating user input. + */ + NATIVE_EVENTS: string; /** * Describes the platform the browser is running on. Will be one of @@ -1394,54 +2595,50 @@ declare module webdriver { * session, ANY may be used to indicate no platform preference (this is * semantically equivalent to omitting the platform capability). */ - static PLATFORM: string; + PLATFORM: string; /** * Describes the proxy configuration to use for a new WebDriver session. */ - static PROXY: string; + PROXY: string; /** Whether the driver supports changing the brower's orientation. */ - static ROTATABLE: string; + ROTATABLE: string; /** * Whether a driver is only capable of handling secure SSL certs. To request * that a driver accept insecure SSL certs by default, use * {@link webdriver.Capability.ACCEPT_SSL_CERTS}. */ - static SECURE_SSL: string; + SECURE_SSL: string; /** Whether the driver supports manipulating the app cache. */ - static SUPPORTS_APPLICATION_CACHE: string; - - /** - * Whether the driver supports controlling the browser's internet - * connectivity. - */ - static SUPPORTS_BROWSER_CONNECTION: string; + SUPPORTS_APPLICATION_CACHE: string; /** Whether the driver supports locating elements with CSS selectors. */ - static SUPPORTS_CSS_SELECTORS: string; + SUPPORTS_CSS_SELECTORS: string; /** Whether the browser supports JavaScript. */ - static SUPPORTS_JAVASCRIPT: string; + SUPPORTS_JAVASCRIPT: string; /** Whether the driver supports controlling the browser's location info. */ - static SUPPORTS_LOCATION_CONTEXT: string; + SUPPORTS_LOCATION_CONTEXT: string; /** Whether the driver supports taking screenshots. */ - static TAKES_SCREENSHOT: string; + TAKES_SCREENSHOT: string; /** * Defines how the driver should handle unexpected alerts. The value should * be one of "accept", "dismiss", or "ignore. */ - static UNEXPECTED_ALERT_BEHAVIOR: string; + UNEXPECTED_ALERT_BEHAVIOR: string; /** Defines the browser version. */ - static VERSION: string; + VERSION: string; } + var Capability: ICapability; + class Capabilities { //region Constructors @@ -1478,6 +2675,51 @@ declare module webdriver { */ set(key: string, value: any): Capabilities; + /** + * Sets the logging preferences. Preferences may be specified as a + * {@link webdriver.logging.Preferences} instance, or a as a map of log-type to + * log-level. + * @param {!(webdriver.logging.Preferences|Object.)} prefs The + * logging preferences. + * @return {!webdriver.Capabilities} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Capabilities; + setLoggingPrefs(prefs: { [key: string]: string }): Capabilities; + + + /** + * Sets the proxy configuration for this instance. + * @param {webdriver.ProxyConfig} proxy The desired proxy configuration. + * @return {!webdriver.Capabilities} A self reference. + */ + setProxy(proxy: ProxyConfig): Capabilities; + + + /** + * Sets whether native events should be used. + * @param {boolean} enabled Whether to enable native events. + * @return {!webdriver.Capabilities} A self reference. + */ + setEnableNativeEvents(enabled: boolean): Capabilities; + + + /** + * Sets how elements should be scrolled into view for interaction. + * @param {number} behavior The desired scroll behavior: either 0 to align with + * the top of the viewport or 1 to align with the bottom. + * @return {!webdriver.Capabilities} A self reference. + */ + setScrollBehavior(behavior: number): Capabilities; + + /** + * Sets the default action to take with an unexpected alert before returning + * an error. + * @param {string} behavior The desired behavior; should be "accept", "dismiss", + * or "ignore". Defaults to "dismiss". + * @return {!webdriver.Capabilities} A self reference. + */ + setAlertBehavior(behavior: string): Capabilities; + /** * @param {string} key The capability to return. * @return {*} The capability with the given key, or {@code null} if it has @@ -1558,129 +2800,130 @@ declare module webdriver { /** * An enumeration of valid command string. - * NOTE: A Class was used instead of an Enum so that the class could be extended in Protractor. */ - class CommandName { - static GET_SERVER_STATUS: string; + interface ICommandName { + GET_SERVER_STATUS: string; - static NEW_SESSION: string; - static GET_SESSIONS: string; - static DESCRIBE_SESSION: string; + NEW_SESSION: string; + GET_SESSIONS: string; + DESCRIBE_SESSION: string; - static CLOSE: string; - static QUIT: string; + CLOSE: string; + QUIT: string; - static GET_CURRENT_URL: string; - static GET: string; - static GO_BACK: string; - static GO_FORWARD: string; - static REFRESH: string; + GET_CURRENT_URL: string; + GET: string; + GO_BACK: string; + GO_FORWARD: string; + REFRESH: string; - static ADD_COOKIE: string; - static GET_COOKIE: string; - static GET_ALL_COOKIES: string; - static DELETE_COOKIE: string; - static DELETE_ALL_COOKIES: string; + ADD_COOKIE: string; + GET_COOKIE: string; + GET_ALL_COOKIES: string; + DELETE_COOKIE: string; + DELETE_ALL_COOKIES: string; - static GET_ACTIVE_ELEMENT: string; - static FIND_ELEMENT: string; - static FIND_ELEMENTS: string; - static FIND_CHILD_ELEMENT: string; - static FIND_CHILD_ELEMENTS: string; + GET_ACTIVE_ELEMENT: string; + FIND_ELEMENT: string; + FIND_ELEMENTS: string; + FIND_CHILD_ELEMENT: string; + FIND_CHILD_ELEMENTS: string; - static CLEAR_ELEMENT: string; - static CLICK_ELEMENT: string; - static SEND_KEYS_TO_ELEMENT: string; - static SUBMIT_ELEMENT: string; + CLEAR_ELEMENT: string; + CLICK_ELEMENT: string; + SEND_KEYS_TO_ELEMENT: string; + SUBMIT_ELEMENT: string; - static GET_CURRENT_WINDOW_HANDLE: string; - static GET_WINDOW_HANDLES: string; - static GET_WINDOW_POSITION: string; - static SET_WINDOW_POSITION: string; - static GET_WINDOW_SIZE: string; - static SET_WINDOW_SIZE: string; - static MAXIMIZE_WINDOW: string; + GET_CURRENT_WINDOW_HANDLE: string; + GET_WINDOW_HANDLES: string; + GET_WINDOW_POSITION: string; + SET_WINDOW_POSITION: string; + GET_WINDOW_SIZE: string; + SET_WINDOW_SIZE: string; + MAXIMIZE_WINDOW: string; - static SWITCH_TO_WINDOW: string; - static SWITCH_TO_FRAME: string; - static GET_PAGE_SOURCE: string; - static GET_TITLE: string; + SWITCH_TO_WINDOW: string; + SWITCH_TO_FRAME: string; + GET_PAGE_SOURCE: string; + GET_TITLE: string; - static EXECUTE_SCRIPT: string; - static EXECUTE_ASYNC_SCRIPT: string; + EXECUTE_SCRIPT: string; + EXECUTE_ASYNC_SCRIPT: string; - static GET_ELEMENT_TEXT: string; - static GET_ELEMENT_TAG_NAME: string; - static IS_ELEMENT_SELECTED: string; - static IS_ELEMENT_ENABLED: string; - static IS_ELEMENT_DISPLAYED: string; - static GET_ELEMENT_LOCATION: string; - static GET_ELEMENT_LOCATION_IN_VIEW: string; - static GET_ELEMENT_SIZE: string; - static GET_ELEMENT_ATTRIBUTE: string; - static GET_ELEMENT_VALUE_OF_CSS_PROPERTY: string; - static ELEMENT_EQUALS: string; + GET_ELEMENT_TEXT: string; + GET_ELEMENT_TAG_NAME: string; + IS_ELEMENT_SELECTED: string; + IS_ELEMENT_ENABLED: string; + IS_ELEMENT_DISPLAYED: string; + GET_ELEMENT_LOCATION: string; + GET_ELEMENT_LOCATION_IN_VIEW: string; + GET_ELEMENT_SIZE: string; + GET_ELEMENT_ATTRIBUTE: string; + GET_ELEMENT_VALUE_OF_CSS_PROPERTY: string; + ELEMENT_EQUALS: string; - static SCREENSHOT: string; - static IMPLICITLY_WAIT: string; - static SET_SCRIPT_TIMEOUT: string; - static SET_TIMEOUT: string; + SCREENSHOT: string; + IMPLICITLY_WAIT: string; + SET_SCRIPT_TIMEOUT: string; + SET_TIMEOUT: string; - static ACCEPT_ALERT: string; - static DISMISS_ALERT: string; - static GET_ALERT_TEXT: string; - static SET_ALERT_TEXT: string; + ACCEPT_ALERT: string; + DISMISS_ALERT: string; + GET_ALERT_TEXT: string; + SET_ALERT_TEXT: string; - static EXECUTE_SQL: string; - static GET_LOCATION: string; - static SET_LOCATION: string; - static GET_APP_CACHE: string; - static GET_APP_CACHE_STATUS: string; - static CLEAR_APP_CACHE: string; - static IS_BROWSER_ONLINE: string; - static SET_BROWSER_ONLINE: string; + EXECUTE_SQL: string; + GET_LOCATION: string; + SET_LOCATION: string; + GET_APP_CACHE: string; + GET_APP_CACHE_STATUS: string; + CLEAR_APP_CACHE: string; + IS_BROWSER_ONLINE: string; + SET_BROWSER_ONLINE: string; - static GET_LOCAL_STORAGE_ITEM: string; - static GET_LOCAL_STORAGE_KEYS: string; - static SET_LOCAL_STORAGE_ITEM: string; - static REMOVE_LOCAL_STORAGE_ITEM: string; - static CLEAR_LOCAL_STORAGE: string; - static GET_LOCAL_STORAGE_SIZE: string; + GET_LOCAL_STORAGE_ITEM: string; + GET_LOCAL_STORAGE_KEYS: string; + SET_LOCAL_STORAGE_ITEM: string; + REMOVE_LOCAL_STORAGE_ITEM: string; + CLEAR_LOCAL_STORAGE: string; + GET_LOCAL_STORAGE_SIZE: string; - static GET_SESSION_STORAGE_ITEM: string; - static GET_SESSION_STORAGE_KEYS: string; - static SET_SESSION_STORAGE_ITEM: string; - static REMOVE_SESSION_STORAGE_ITEM: string; - static CLEAR_SESSION_STORAGE: string; - static GET_SESSION_STORAGE_SIZE: string; + GET_SESSION_STORAGE_ITEM: string; + GET_SESSION_STORAGE_KEYS: string; + SET_SESSION_STORAGE_ITEM: string; + REMOVE_SESSION_STORAGE_ITEM: string; + CLEAR_SESSION_STORAGE: string; + GET_SESSION_STORAGE_SIZE: string; - static SET_SCREEN_ORIENTATION: string; - static GET_SCREEN_ORIENTATION: string; + SET_SCREEN_ORIENTATION: string; + GET_SCREEN_ORIENTATION: string; // These belong to the Advanced user interactions - an element is // optional for these commands. - static CLICK: string; - static DOUBLE_CLICK: string; - static MOUSE_DOWN: string; - static MOUSE_UP: string; - static MOVE_TO: string; - static SEND_KEYS_TO_ACTIVE_ELEMENT: string; + CLICK: string; + DOUBLE_CLICK: string; + MOUSE_DOWN: string; + MOUSE_UP: string; + MOVE_TO: string; + SEND_KEYS_TO_ACTIVE_ELEMENT: string; // These belong to the Advanced Touch API - static TOUCH_SINGLE_TAP: string; - static TOUCH_DOWN: string; - static TOUCH_UP: string; - static TOUCH_MOVE: string; - static TOUCH_SCROLL: string; - static TOUCH_DOUBLE_TAP: string; - static TOUCH_LONG_PRESS: string; - static TOUCH_FLICK: string; + TOUCH_SINGLE_TAP: string; + TOUCH_DOWN: string; + TOUCH_UP: string; + TOUCH_MOVE: string; + TOUCH_SCROLL: string; + TOUCH_DOUBLE_TAP: string; + TOUCH_LONG_PRESS: string; + TOUCH_FLICK: string; - static GET_AVAILABLE_LOG_TYPES: string; - static GET_LOG: string; - static GET_SESSION_LOGS: string; + GET_AVAILABLE_LOG_TYPES: string; + GET_LOG: string; + GET_SESSION_LOGS: string; } + var CommandName: ICommandName; + /** * Describes a command to be executed by the WebDriverJS framework. * @param {!webdriver.CommandName} name The name of this command. @@ -1710,14 +2953,14 @@ declare module webdriver { * @param {*} value The parameter value. * @return {!webdriver.Command} A self reference. */ - setParameter(name: string, value: any): webdriver.Command; + setParameter(name: string, value: any): Command; /** * Sets the parameters for this command. * @param {!Object.<*>} parameters The command parameters. * @return {!webdriver.Command} A self reference. */ - setParameters(parameters: any): webdriver.Command; + setParameters(parameters: any): Command; /** * Returns a named command parameter. @@ -1747,7 +2990,7 @@ declare module webdriver { * @param {function(Error, !bot.response.ResponseObject=)} callback the function * to invoke when the command response is ready. */ - execute(command: webdriver.Command, callback: (error: Error, responseObject: any) => any ): void; + execute(command: Command, callback: (error: Error, responseObject: any) => any ): void; } /** @@ -1781,7 +3024,7 @@ declare module webdriver { * scope: (Object|undefined)}>} The registered listeners for * the given event type. */ - listeners(type: string): Array<{fn: any; oneshot: boolean; scope: any;}>; + listeners(type: string): Array<{fn: Function; oneshot: boolean; scope: any;}>; /** * Registers a listener. @@ -1790,7 +3033,7 @@ declare module webdriver { * @param {Object=} opt_scope The object in whose scope to invoke the listener. * @return {!webdriver.EventEmitter} A self reference. */ - addListener(type: string, listenerFn: any, opt_scope?:any): EventEmitter; + addListener(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; /** * Registers a one-time listener which will be called only the first time an @@ -1809,7 +3052,7 @@ declare module webdriver { * @param {Object=} opt_scope The object in whose scope to invoke the listener. * @return {!webdriver.EventEmitter} A self reference. */ - on(type: string, listenerFn: any, opt_scope?:any): EventEmitter; + on(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; /** * Removes a previously registered event listener. @@ -1817,7 +3060,7 @@ declare module webdriver { * @param {!Function} listenerFn The handler function to remove. * @return {!webdriver.EventEmitter} A self reference. */ - removeListener(type: string, listenerFn: any): EventEmitter; + removeListener(type: string, listenerFn: Function): EventEmitter; /** * Removes all listeners for a specific type of event. If no event is @@ -1830,48 +3073,17 @@ declare module webdriver { //endregion } - /** - * @implements {webdriver.CommandExecutor} - */ - class FirefoxDomExecutor implements webdriver.CommandExecutor { - //region Constructors - - /** - * @constructor - */ - constructor(); - - //endregion - - //region Static Methods - - /** - * @return {boolean} Whether the current environment supports the - * FirefoxDomExecutor. - */ - static isAvailable(): boolean; - - //endretion - - //region Methods - - /** @override */ - execute(command: webdriver.Command, callback: (error: Error, responseObject: any) => any ): void; - - //endregion - } - /** * Interface for navigating back and forth in the browser history. */ - class WebDriverNavigation { + interface WebDriverNavigation { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: WebDriver): WebDriverNavigation; //endregion @@ -1883,43 +3095,52 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved when the * URL has been loaded. */ - to(url: string): webdriver.promise.Promise; + to(url: string): webdriver.promise.Promise; /** * Schedules a command to move backwards in the browser history. * @return {!webdriver.promise.Promise} A promise that will be resolved when the * navigation event has completed. */ - back(): webdriver.promise.Promise; + back(): webdriver.promise.Promise; /** * Schedules a command to move forwards in the browser history. * @return {!webdriver.promise.Promise} A promise that will be resolved when the * navigation event has completed. */ - forward(): webdriver.promise.Promise; + forward(): webdriver.promise.Promise; /** * Schedules a command to refresh the current page. * @return {!webdriver.promise.Promise} A promise that will be resolved when the * navigation event has completed. */ - refresh(): webdriver.promise.Promise; + refresh(): webdriver.promise.Promise; //endregion } + interface IWebDriverOptionsCookie { + name: string; + value: string; + path?: string; + domain?: string; + secure?: boolean; + expiry?: number; + } + /** * Provides methods for managing browser and driver state. */ - class WebDriverOptions { + interface WebDriverOptions { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: webdriver.WebDriver): WebDriverOptions; //endregion @@ -1937,15 +3158,15 @@ declare module webdriver { * @return {!webdriver.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): webdriver.promise.Promise; + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: Date): webdriver.promise.Promise; /** * Schedules a command to delete all cookies visible to the current page. * @return {!webdriver.promise.Promise} A promise that will be resolved when all * cookies have been deleted. */ - deleteAllCookies(): webdriver.promise.Promise; + deleteAllCookies(): webdriver.promise.Promise; /** * Schedules a command to delete the cookie with the given name. This command is @@ -1955,7 +3176,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved when the * cookie has been deleted. */ - deleteCookie(name: string): webdriver.promise.Promise; + deleteCookie(name: string): webdriver.promise.Promise; /** * Schedules a command to retrieve all cookies visible to the current page. @@ -1965,7 +3186,7 @@ declare module webdriver { * cookies visible to the current page. * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object */ - getCookies(): webdriver.promise.Promise; + getCookies(): webdriver.promise.Promise; /** * Schedules a command to retrieve the cookie with the given name. Returns null @@ -1976,25 +3197,25 @@ declare module webdriver { * named cookie, or {@code null} if there is no such cookie. * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object */ - getCookie(name: string): webdriver.promise.Promise; + getCookie(name: string): webdriver.promise.Promise; /** * @return {!webdriver.WebDriver.Logs} The interface for managing driver * logs. */ - logs(): webdriver.WebDriverLogs; + logs(): WebDriverLogs; /** * @return {!webdriver.WebDriver.Timeouts} The interface for managing driver * timeouts. */ - timeouts(): webdriver.WebDriverTimeouts; + timeouts(): WebDriverTimeouts; /** * @return {!webdriver.WebDriver.Window} The interface for managing the * current window. */ - window(): webdriver.WebDriverWindow; + window(): WebDriverWindow; //endregion } @@ -2002,14 +3223,14 @@ declare module webdriver { /** * An interface for managing timeout behavior for WebDriver instances. */ - class WebDriverTimeouts { + interface WebDriverTimeouts { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: WebDriver): WebDriverTimeouts; //endregion @@ -2036,7 +3257,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved when the * implicit wait timeout has been set. */ - implicitlyWait(ms: number): webdriver.promise.Promise; + implicitlyWait(ms: number): webdriver.promise.Promise; /** * Sets the amount of time to wait, in milliseconds, for an asynchronous script @@ -2047,7 +3268,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved when the * script timeout has been set. */ - setScriptTimeout(ms: number): webdriver.promise.Promise; + setScriptTimeout(ms: number): webdriver.promise.Promise; /** * Sets the amount of time to wait for a page load to complete before returning @@ -2056,7 +3277,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved when * the timeout has been set. */ - pageLoadTimeout(ms: number): webdriver.promise.Promise; + pageLoadTimeout(ms: number): webdriver.promise.Promise; //endregion } @@ -2064,7 +3285,7 @@ declare module webdriver { /** * An interface for managing the current window. */ - class WebDriverWindow { + interface WebDriverWindow { //region Constructors @@ -2072,7 +3293,7 @@ declare module webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: WebDriver): WebDriverWindow; //endregion @@ -2084,7 +3305,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved with the * window's position in the form of a {x:number, y:number} object literal. */ - getPosition(): webdriver.promise.Promise; + getPosition(): webdriver.promise.Promise; /** * Repositions the current window. @@ -2095,7 +3316,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved when the * command has completed. */ - setPosition(x: number, y: number): webdriver.promise.Promise; + setPosition(x: number, y: number): webdriver.promise.Promise; /** * Retrieves the window's current size. @@ -2103,7 +3324,7 @@ declare module webdriver { * window's size in the form of a {width:number, height:number} object * literal. */ - getSize(): webdriver.promise.Promise; + getSize(): webdriver.promise.Promise; /** * Resizes the current window. @@ -2112,14 +3333,14 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved when the * command has completed. */ - setSize(width: number, height: number): webdriver.promise.Promise; + setSize(width: number, height: number): webdriver.promise.Promise; /** * Maximizes the current window. * @return {!webdriver.promise.Promise} A promise that will be resolved when the * command has completed. */ - maximize(): webdriver.promise.Promise; + maximize(): webdriver.promise.Promise; //endregion } @@ -2127,7 +3348,7 @@ declare module webdriver { /** * Interface for managing WebDriver log records. */ - class WebDriverLogs { + interface WebDriverLogs { //region Constructors @@ -2135,7 +3356,7 @@ declare module webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: WebDriver): WebDriverLogs; //endregion @@ -2155,14 +3376,14 @@ declare module webdriver { * promise that will resolve to a list of log entries for the specified * type. */ - get(type: string): webdriver.promise.Promise; + get(type: string): webdriver.promise.Promise; /** * Retrieves the log types available to this driver. * @return {!webdriver.promise.Promise.>} A * promise that will resolve to a list of available log types. */ - getAvailableLogTypes(): webdriver.promise.Promise; + getAvailableLogTypes(): webdriver.promise.Promise; //endregion } @@ -2170,7 +3391,7 @@ declare module webdriver { /** * An interface for changing the focus of the driver to another frame or window. */ - class WebDriverTargetLocator { + interface WebDriverTargetLocator { //region Constructors @@ -2178,7 +3399,7 @@ declare module webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: WebDriver): WebDriverTargetLocator; //endregion @@ -2190,7 +3411,7 @@ declare module webdriver { * available. * @return {!webdriver.WebElement} The active element. */ - activeElement(): webdriver.WebElement; + activeElement(): WebElementPromise; /** * Schedules a command to switch focus of all future commands to the first frame @@ -2198,7 +3419,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved when the * driver has changed focus to the default content. */ - defaultContent(): webdriver.promise.Promise; + defaultContent(): webdriver.promise.Promise; /** * Schedules a command to switch the focus of all future commands to another @@ -2218,8 +3439,8 @@ declare module webdriver { * @return {!webdriver.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: string): webdriver.promise.Promise; + frame(nameOrIndex: number): webdriver.promise.Promise; /** * Schedules a command to switch the focus of all future commands to another @@ -2233,7 +3454,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved when the * driver has changed focus to the specified window. */ - window(nameOrHandle: string): webdriver.promise.Promise; + window(nameOrHandle: string): webdriver.promise.Promise; /** * Schedules a command to change focus to the active alert dialog. This command @@ -2241,7 +3462,7 @@ declare module webdriver { * dialog is not currently open. * @return {!webdriver.Alert} The open alert. */ - alert(): webdriver.Alert; + alert(): AlertPromise; //endregion } @@ -2277,8 +3498,8 @@ declare module webdriver { * schedule commands through. Defaults to the active flow object. * @constructor */ - constructor(session: webdriver.Session, executor: webdriver.CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); - constructor(session: webdriver.promise.Promise, executor: webdriver.CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); + constructor(session: Session, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); + constructor(session: webdriver.promise.Promise, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); //endregion @@ -2300,9 +3521,12 @@ declare module webdriver { * @param {!webdriver.CommandExecutor} 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. */ - static attachToSession(executor: webdriver.CommandExecutor, sessionId: string): WebDriver; + static attachToSession(executor: CommandExecutor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; /** * Creates a new WebDriver session. @@ -2310,9 +3534,13 @@ declare module webdriver { * session with. * @param {!webdriver.Capabilities} desiredCapabilities The desired * capabilities for the new session. + * @param {webdriver.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} + * control flow. * @return {!webdriver.WebDriver} The driver for the newly created session. */ - static createSession(executor: webdriver.CommandExecutor, desiredCapabilities: webdriver.Capabilities): WebDriver; + static createSession(executor: CommandExecutor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; //endregion @@ -2332,18 +3560,18 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved with * the command result. */ - schedule(command: webdriver.Command, description: string): webdriver.promise.Promise; + schedule(command: Command, description: string): webdriver.promise.Promise; /** * @return {!webdriver.promise.Promise} A promise for this client's session. */ - getSession(): webdriver.promise.Promise; + getSession(): webdriver.promise.Promise; /** * @return {!webdriver.promise.Promise} A promise that will resolve with the * this instance's capabilities. */ - getCapabilities(): webdriver.promise.Promise; + getCapabilities(): webdriver.promise.Promise; /** * Schedules a command to quit the current session. After calling quit, this @@ -2352,7 +3580,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved when * the command has completed. */ - quit(): webdriver.promise.Promise; + quit(): webdriver.promise.Promise; /** * Creates a new action sequence using this driver. The sequence will not be @@ -2367,7 +3595,7 @@ declare module webdriver { * * @return {!webdriver.ActionSequence} A new action sequence for this instance. */ - actions(): webdriver.ActionSequence; + actions(): ActionSequence; /** * Schedules a command to execute JavaScript in the context of the currently @@ -2406,8 +3634,8 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will resolve to the * scripts return value. */ - executeScript(script: string, ...var_args: any[]): webdriver.promise.Promise; - executeScript(script: any, ...var_args: any[]): webdriver.promise.Promise; + executeScript(script: string, ...var_args: any[]): webdriver.promise.Promise; + executeScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; /** * Schedules a command to execute asynchronous JavaScript in the context of the @@ -2488,8 +3716,8 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will resolve to the * scripts return value. */ - executeAsyncScript(script: string, ...var_args: any[]): webdriver.promise.Promise; - executeAsyncScript(script: any, ...var_args: any[]): webdriver.promise.Promise; + executeAsyncScript(script: string, ...var_args: any[]): webdriver.promise.Promise; + executeAsyncScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; /** * Schedules a command to execute a custom function. @@ -2499,21 +3727,31 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved with the * function's result. */ - call(fn: any, opt_scope?: any, ...var_args: any[]): webdriver.promise.Promise; + call(fn: Function, opt_scope?: any, ...var_args: any[]): webdriver.promise.Promise; /** * Schedules a command to wait for a condition to hold, as defined by some * user supplied function. If any errors occur while evaluating the wait, they * will be allowed to propagate. - * @param {function():boolean|!webdriver.promise.Promise} fn The function to - * evaluate as a wait condition. + * + *

In the event a condition returns a {@link webdriver.promise.Promise}, the + * polling loop will wait for it to be resolved and use the resolved value for + * evaluating whether the condition has been satisfied. The resolution time for + * a promise is factored into whether a wait has timed out. + * + * @param {!(webdriver.until.Condition.| + * function(!webdriver.WebDriver): T)} condition Either a condition + * object, or a function to evaluate as a condition. * @param {number} timeout How long to wait for the condition to be true. * @param {string=} opt_message An optional message to use if the wait times * out. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * wait condition has been satisfied. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the first truthy value returned by the condition function, or + * rejected if the condition times out. + * @template T */ - wait(fn: () => any, timeout: number, opt_message?: string): webdriver.promise.Promise; + wait(condition: webdriver.until.Condition, timeout: number, opt_message?: string): webdriver.promise.Promise; + wait(condition: (webdriver: WebDriver) => any, timeout: number, opt_message?: string): webdriver.promise.Promise; /** * Schedules a command to make the driver sleep for the given amount of time. @@ -2521,21 +3759,21 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved when the * sleep has finished. */ - sleep(ms: number): webdriver.promise.Promise; + sleep(ms: number): webdriver.promise.Promise; /** * Schedules a command to retrieve they current window handle. * @return {!webdriver.promise.Promise} A promise that will be resolved with the * current window handle. */ - getWindowHandle(): webdriver.promise.Promise; + getWindowHandle(): webdriver.promise.Promise; /** * Schedules a command to retrieve the current list of available window handles. * @return {!webdriver.promise.Promise} A promise that will be resolved with an * array of window handles. */ - getAllWindowHandles(): webdriver.promise.Promise; + getAllWindowHandles(): webdriver.promise.Promise; /** * Schedules a command to retrieve the current page's source. The page source @@ -2545,14 +3783,14 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved with the * current page source. */ - getPageSource(): webdriver.promise.Promise; + getPageSource(): webdriver.promise.Promise; /** * Schedules a command to close the current window. * @return {!webdriver.promise.Promise} A promise that will be resolved when * this command has completed. */ - close(): webdriver.promise.Promise; + close(): webdriver.promise.Promise; /** * Schedules a command to navigate to the given URL. @@ -2560,21 +3798,21 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved when the * document has finished loading. */ - get(url: string): webdriver.promise.Promise; + get(url: string): webdriver.promise.Promise; /** * Schedules a command to retrieve the URL of the current page. * @return {!webdriver.promise.Promise} A promise that will be resolved with the * current URL. */ - getCurrentUrl(): webdriver.promise.Promise; + getCurrentUrl(): webdriver.promise.Promise; /** * Schedules a command to retrieve the current page's title. * @return {!webdriver.promise.Promise} A promise that will be resolved with the * current page's title. */ - getTitle(): webdriver.promise.Promise; + getTitle(): webdriver.promise.Promise; /** * Schedule a command to find an element on the page. If the element cannot be @@ -2612,8 +3850,8 @@ declare module webdriver { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locatorOrElement: webdriver.Locator, ...var_args: any[]): webdriver.WebElement; - findElement(locatorOrElement: any, ...var_args: any[]): webdriver.WebElement; + findElement(locatorOrElement: Locator, ...var_args: any[]): WebElementPromise; + findElement(locatorOrElement: any, ...var_args: any[]): WebElementPromise; /** * Schedules a command to test if an element is present on the page. @@ -2630,8 +3868,8 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will resolve to whether * the element is present on the page. */ - isElementPresent(locatorOrElement: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; - isElementPresent(locatorOrElement: any, ...var_args: any[]): webdriver.promise.Promise; + isElementPresent(locatorOrElement: Locator, ...var_args: any[]): webdriver.promise.Promise; + isElementPresent(locatorOrElement: any, ...var_args: any[]): webdriver.promise.Promise; /** * Schedule a command to search for multiple elements on the page. @@ -2643,8 +3881,8 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved to an * array of the located {@link webdriver.WebElement}s. */ - findElements(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; - findElements(locator: any, ...var_args: any[]): webdriver.promise.Promise; + findElements(locator: Locator, ...var_args: any[]): webdriver.promise.Promise; + findElements(locator: any, ...var_args: any[]): webdriver.promise.Promise; /** * Schedule a command to take a screenshot. The driver makes a best effort to @@ -2659,166 +3897,66 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved to the * screenshot as a base-64 encoded PNG. */ - takeScreenshot(): webdriver.promise.Promise; + takeScreenshot(): webdriver.promise.Promise; /** * @return {!webdriver.WebDriver.Options} The options interface for this * instance. */ - manage(): webdriver.WebDriverOptions; + manage(): WebDriverOptions; /** * @return {!webdriver.WebDriver.Navigation} The navigation interface for this * instance. */ - navigate(): webdriver.WebDriverNavigation; + navigate(): WebDriverNavigation; /** * @return {!webdriver.WebDriver.TargetLocator} The target locator interface for * this instance. */ - switchTo(): webdriver.WebDriverTargetLocator + switchTo(): WebDriverTargetLocator; //endregion } + interface IWebElementId { + ELEMENT: string; + } + /** * Represents a DOM element. WebElements can be found by searching from the * document root using a {@code webdriver.WebDriver} instance, or by searching * under another {@code webdriver.WebElement}: - * + *


      *   driver.get('http://www.google.com');
      *   var searchForm = driver.findElement(By.tagName('form'));
      *   var searchBox = searchForm.findElement(By.name('q'));
      *   searchBox.sendKeys('webdriver');
+     * 
* * The WebElement is implemented as a promise for compatibility with the promise * API. It will always resolve itself when its internal state has been fully * resolved and commands may be issued against the element. This can be used to * catch errors when an element cannot be located on the page: - * + *

      *   driver.findElement(By.id('not-there')).then(function(element) {
      *     alert('Found an element that was not expected to be there!');
      *   }, function(error) {
      *     alert('The element was not found, as expected');
      *   });
-     *
-     * @extends {webdriver.promise.Deferred}
+     * 
*/ - class WebElement extends webdriver.promise.Deferred { - //region Constructors - - /** - * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this - * element. - * @param {!(string|webdriver.promise.Promise)} id Either the opaque ID for the - * underlying DOM element assigned by the server, or a promise that will - * resolve to that ID or another WebElement. - * @constructor - */ - constructor(driver: webdriver.WebDriver, id: webdriver.promise.Promise); - constructor(driver: webdriver.WebDriver, id: string); - - //endregion - - //region Static Properties - - /** - * The property key used in the wire protocol to indicate that a JSON object - * contains the ID of a WebElement. - * @type {string} - * @const - */ - static ELEMENT_KEY: string; - - //endregion + interface IWebElement { //region Methods - /** - * @return {!webdriver.WebDriver} The parent driver for this instance. - */ - getDriver(): webdriver.WebDriver; - - /** - * @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 - */ - toWireValue(): webdriver.promise.Promise; - - /** - * Schedule a command to find a descendant of this element. If the element - * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will - * be returned by the driver. Unlike other commands, this error cannot be - * suppressed. In other words, scheduling a command to find an element doubles - * as an assert that the element is present on the page. To test whether an - * element is present on the page, use {@code #isElementPresent} instead. - *

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

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

- * Note that JS locator searches cannot be restricted to a subtree. All such - * searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {webdriver.WebElement} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. - */ - findElement(locator: webdriver.Locator, ...var_args: any[]): WebElement; - findElement(locator: any, ...var_args: any[]): WebElement; - - /** - * Schedules a command to test if there is at least one descendant of this - * element that matches the given search criteria. - * - *

Note that JS locator searches cannot be restricted to a subtree of the - * DOM. All such searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether an element could be located on the page. - */ - isElementPresent(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; - isElementPresent(locator: any, ...var_args: any[]): webdriver.promise.Promise; - - /** - * Schedules a command to find all of the descendants of this element that match - * the given search criteria. - *

- * Note that JS locator searches cannot be restricted to a subtree. All such - * searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the elements. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {!webdriver.promise.Promise} A promise that will be resolved with an - * array of located {@link webdriver.WebElement}s. - */ - findElements(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; - findElements(locator: any, ...var_args: any[]): webdriver.promise.Promise; - /** * 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; + click(): webdriver.promise.Promise; /** * Schedules a command to type a sequence on the DOM element represented by this @@ -2860,14 +3998,14 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved when all * keys have been typed. */ - sendKeys(...var_args: string[]): webdriver.promise.Promise; + 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; + getTagName(): webdriver.promise.Promise; /** * Schedules a command to query for the computed style of the element @@ -2884,7 +4022,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved with the * requested CSS value. */ - getCssValue(cssStyleProperty: string): webdriver.promise.Promise; + getCssValue(cssStyleProperty: string): webdriver.promise.Promise; /** * Schedules a command to query for the value of the given attribute of the @@ -2913,7 +4051,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved with the * attribute's value. */ - getAttribute(attributeName: string): webdriver.promise.Promise; + getAttribute(attributeName: string): webdriver.promise.Promise; /** * Get the visible (i.e. not hidden by CSS) innerText of this element, including @@ -2921,7 +4059,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved with the * element's visible text. */ - getText(): webdriver.promise.Promise; + getText(): webdriver.promise.Promise; /** * Schedules a command to compute the size of this element's bounding box, in @@ -2929,14 +4067,14 @@ declare module webdriver { * @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; + 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; + getLocation(): webdriver.promise.Promise; /** * Schedules a command to query whether the DOM element represented by this @@ -2944,14 +4082,14 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved with * whether this element is currently enabled. */ - isEnabled(): webdriver.promise.Promise; + 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; + isSelected(): webdriver.promise.Promise; /** * Schedules a command to submit the form containing this element (or this @@ -2960,7 +4098,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved when * the form has been submitted. */ - submit(): webdriver.promise.Promise; + submit(): webdriver.promise.Promise; /** * Schedules a command to clear the {@code value} of this element. This command @@ -2969,28 +4107,397 @@ declare module webdriver { * @return {!webdriver.promise.Promise} A promise that will be resolved when * the element has been cleared. */ - clear(): webdriver.promise.Promise; + 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; + 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; + 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; + getInnerHtml(): webdriver.promise.Promise; + + //endregion + } + + interface IWebElementFinders { + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + * + *

The search criteria for an element may be defined using one of the + * factories in the {@link webdriver.By} namespace, or as a short-hand + * {@link webdriver.By.Hash} object. For example, the following two statements + * are equivalent: + *

+         * var e1 = element.findElement(By.id('foo'));
+         * var e2 = element.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: + *

+         * var link = element.findElement(firstVisibleLink);
+         *
+         * function firstVisibleLink(element) {
+         *   var links = element.findElements(By.tagName('a'));
+         *   return webdriver.promise.filter(links, function(link) {
+         *     return links.isDisplayed();
+         *   }).then(function(visibleLinks) {
+         *     return visibleLinks[0];
+         *   });
+         * }
+         * 
+ * + * @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 + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: Locator): WebElementPromise; + findElement(locator: any): 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 + * resolved with whether an element could be located on the page. + */ + isElementPresent(locator: Locator): webdriver.promise.Promise; + isElementPresent(locator: any): 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 + * promise that will resolve to an array of WebElements. + */ + findElements(locator: Locator): webdriver.promise.Promise; + findElements(locator: any): webdriver.promise.Promise; + } + + class WebElement implements IWebElement, IWebElementFinders { + //region Constructors + + /** + * @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 + */ + constructor(driver: WebDriver, id: webdriver.promise.Promise); + constructor(driver: WebDriver, id: IWebElementId); + + //endregion + + //region Static Properties + + /** + * The property key used in the wire protocol to indicate that a JSON object + * contains the ID of a WebElement. + * @type {string} + * @const + */ + static ELEMENT_KEY: string; + + //endregion + + //region Methods + + /** + * @return {!webdriver.WebDriver} The parent driver for this instance. + */ + getDriver(): WebDriver; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + * + *

The search criteria for an element may be defined using one of the + * factories in the {@link webdriver.By} namespace, or as a short-hand + * {@link webdriver.By.Hash} object. For example, the following two statements + * are equivalent: + *

+         * var e1 = element.findElement(By.id('foo'));
+         * var e2 = element.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: + *

+         * var link = element.findElement(firstVisibleLink);
+         *
+         * function firstVisibleLink(element) {
+         *   var links = element.findElements(By.tagName('a'));
+         *   return webdriver.promise.filter(links, function(link) {
+         *     return links.isDisplayed();
+         *   }).then(function(visibleLinks) {
+         *     return visibleLinks[0];
+         *   });
+         * }
+         * 
+ * + * @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 + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: Locator): WebElementPromise; + findElement(locator: any): 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 + * resolved with whether an element could be located on the page. + */ + isElementPresent(locator: Locator): webdriver.promise.Promise; + isElementPresent(locator: any): 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 + * promise that will resolve to an array of WebElements. + */ + findElements(locator: Locator): webdriver.promise.Promise; + findElements(locator: any): webdriver.promise.Promise; + + /** + * 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; //endregion @@ -3003,24 +4510,141 @@ declare module webdriver { * @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; + static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; //endregion } + /** + * WebElementPromise is a promise that will be fulfilled with a WebElement. + * This serves as a forward proxy on WebElement, allowing calls to be + * scheduled without directly on this instance before the underlying + * WebElement has been fulfilled. In other words, the following two statements + * are equivalent: + *

+     *     driver.findElement({id: 'my-button'}).click();
+     *     driver.findElement({id: 'my-button'}).then(function(el) {
+     *       return el.click();
+     *     });
+     * 
+ * + * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!webdriver.promise.Promise.} el A promise + * that will resolve to the promised element. + * @constructor + * @extends {webdriver.WebElement} + * @implements {webdriver.promise.Thenable.} + * @final + */ + class WebElementPromise extends WebElement implements webdriver.promise.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. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param {?(function(T): (R|webdriver.promise.Promise.))=} 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 {?(function(*): (R|webdriver.promise.Promise.))=} opt_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 + */ + then(opt_callback?: (value: WebElement) => any, opt_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().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 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): webdriver.promise.Promise; + } + interface ILocatorStrategy { className(value: string): Locator; - 'class name'(value: string): Locator; css(value: string): Locator; id(value: string): Locator; - js(value: string): Locator; + js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; linkText(value: string): Locator; - 'link text'(value: string): Locator; name(value: string): Locator; partialLinkText(value: string): Locator; - 'partial link text'(value: string): Locator; tagName(value: string): Locator; - 'tag name'(value: string): Locator; xpath(value: string): Locator; } @@ -3029,19 +4653,7 @@ declare module webdriver { /** * An element locator. */ - class Locator { - - //region Constructors - - /** - * 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); - - //endregion + interface Locator { //region Properties @@ -3059,45 +4671,12 @@ declare module webdriver { //endregion - //region Static Properties - - /** - * Factory methods for the supported locator strategies. - * @type {Object.} - */ - static Strategy: ILocatorStrategy; - - //endregion - //region Methods /** @return {string} String representation of this locator. */ toString(): string; //endregion - - //region Static Methods - - /** - * Creates a new Locator from an object whose only property is also a key in - * the {@code webdriver.Locator.Strategy} map. - * @param {Object.} obj The object to convert into a locator. - * @return {webdriver.Locator} The new locator object. - */ - static createFromObj(obj: any): Locator - - /** - * Verifies that a {@code locator} is a valid locator to use for searching for - * elements on the page. - * @param {webdriver.Locator|Object.} locator The locator - * to verify, or a short-hand object that can be converted into a locator - * to verify. - * @return {!webdriver.Locator} The validated locator. - */ - static checkLocator(locator: Locator): Locator; - static checkLocator(obj: any): Locator; - - //endregion } /** @@ -3113,7 +4692,7 @@ declare module webdriver { * capabilities. * @constructor */ - constructor(id: string, capabilities: webdriver.Capabilities); + constructor(id: string, capabilities: Capabilities); constructor(id: string, capabilities: any); //endregion @@ -3128,7 +4707,7 @@ declare module webdriver { /** * @return {!webdriver.Capabilities} This session's capabilities. */ - getCapabilities(): webdriver.Capabilities; + getCapabilities(): Capabilities; /** * Retrieves the value of a specific capability. @@ -3148,12 +4727,7 @@ declare module webdriver { } } -declare module 'selenium-webdriver' { - export = webdriver; -} - -declare module 'selenium-webdriver/testing' { - +declare module testing { /** * Registers a new test suite. * @param name The suite name. @@ -3215,11 +4789,22 @@ declare module 'selenium-webdriver/testing' { function xit(name: string, fn: Function): void; } -declare module 'selenium-webdriver/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. - */ - function createExecutor(url: any): webdriver.CommandExecutor; +declare module 'selenium-webdriver/chrome' { + export = chrome; } + +declare module 'selenium-webdriver/firefox' { + export = firefox; +} + +declare module 'selenium-webdriver/executors' { + export = executors; +} + +declare module 'selenium-webdriver' { + export = webdriver; +} + +declare module 'selenium-webdriver/testing' { + export = testing; +} \ No newline at end of file