UNPKG

nightwatch

Version:

Easy to use Node.js based end-to-end testing solution for web applications using the W3C WebDriver API.

1,766 lines (1,567 loc) 255 kB
// Type definitions for nightwatch 2.3 // Project: http://nightwatchjs.org // Definitions by: Rahul Kavalapara <https://github.com/rkavalap> // Connor Schlesiger <https://github.com/schlesiger> // Clayton Astrom <https://github.com/ClaytonAstrom> // Lukas Beranek <https://github.com/lloiser> // Vaibhav Singh <https://github.com/vaibhavsingh97> // Andrei Rusu <https://github.com/beatfactor> // David Burns <https://github.com/AutomatedTester> // Ravi Sawlani <https://github.com/gravityvi> // Binayak Ghosh <https://github.com/swrdfish> // Harshit Agrawal <https://github.com/harshit-bs> // David Mello <https://github.com/literallyMello> // Luke Bickell <https://github.com/lukebickell> // Priyansh Garg <https://github.com/garg3133> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 4.5 // Nightwatch Version: 3.0.0 import { Protocol } from 'devtools-protocol'; import { By as SeleniumBy, Actions, Capabilities, WebElement, WebDriver, RelativeBy, locateWith as seleniumLocateWith } from 'selenium-webdriver'; import { Expect } from './expect'; import { Assert } from './assertions'; import { ElementFunction } from './web-element'; import { NightwatchGlobals } from './globals'; import { EnhancedPageObject } from './page-object'; import { NightwatchCustomCommands } from './custom-command'; import { NightwatchDesiredCapabilities } from './desired-capabilities'; import { NightwatchOptions, NightwatchTestOptions } from './nightwatch-options'; import { IfUnknown } from './utils'; export * from './globals'; export * from './expect'; export * from './web-element'; export * from './custom-assertion'; export * from './custom-command'; export * from './page-object'; export * from './desired-capabilities'; export * from './nightwatch-options'; export * from './assertions'; export const ELEMENT_KEY = 'element-6066-11e4-a52e-4f735466cecf'; export interface ElementResult { [ELEMENT_KEY]: string; } export interface JSON_WEB_OBJECT extends ElementResult { getId: () => string; } export type ScopedSelector = string | ElementProperties | Element | SeleniumBy | RelativeBy; export type Definition = ScopedSelector | WebElement; export type NightwatchGenericCallback<T> = ( this: NightwatchAPI, result: NightwatchCallbackResult<T> ) => void export type Awaitable<T, V> = Omit<T, 'then'> & PromiseLike<V>; export type KeysFilter<T, U> = { [K in keyof T]-?: T[K] extends U ? K : never; }[keyof T]; // tslint:disable-next-line type VoidToNull<T> = T extends void ? null : T; type ExecuteScriptFunction<ArgType extends any[], ReturnValue> = (this: { [key: string]: any }, ...args: ArgType) => ReturnValue; type ExecuteAsyncScriptFunction<ArgType extends any[], ReturnValue> = (this: { [key: string]: any }, ...args: [...innerArgs: ArgType, done: (result?: ReturnValue) => void]) => void; export interface AppiumGeolocation { latitude: number; longitude: number; altitude?: number; } export interface NightwatchTestSuite { name: string; module: string; group: string; results: any; } export interface NightwatchEnsureResult { value: null; returned: 1; } export interface Ensure { /** * Ensures that the Nightwatch WebDriver client is able to switch to the designated frame. */ ableToSwitchToFrame( frame: number | WebElement | SeleniumBy ): Awaitable<NightwatchAPI, NightwatchEnsureResult>; /** * Creates a condition that waits for an alert to be opened. */ alertIsPresent(): Awaitable<NightwatchAPI, NightwatchEnsureResult>; /** * Creates a condition that will wait for the given element to be disabled. */ elementIsDisabled( element: WebElement | Element | string ): Awaitable<NightwatchAPI, NightwatchEnsureResult>; /** * Creates a condition that will wait for the given element to be enabled. */ elementIsEnabled( element: WebElement ): Awaitable<NightwatchAPI, NightwatchEnsureResult>; /** * Creates a condition that will wait for the given element to be deselected. */ elementIsNotSelected( element: WebElement | Element | string ): Awaitable<NightwatchAPI, NightwatchEnsureResult>; /** * Creates a condition that will wait for the given element to be in the DOM, yet not displayed to the user. */ elementIsNotVisible( element: WebElement | Element | string ): Awaitable<NightwatchAPI, NightwatchEnsureResult>; /** * Creates a condition that will wait for the given element to be selected. */ elementIsSelected( element: WebElement | Element | string ): Awaitable<NightwatchAPI, NightwatchEnsureResult>; /** * Creates a condition that will wait for the given element to be displayed. */ elementIsVisible( element: WebElement | Element | string ): Awaitable<NightwatchAPI, NightwatchEnsureResult>; /** * Creates a condition that will loop until an element is found with the given locator. */ elementLocated(locator: SeleniumBy): Awaitable<NightwatchAPI, NightwatchEnsureResult>; /** * Creates a condition that will wait for the given element's text to contain the given substring. */ elementTextContains( element: WebElement | Element | string, substr: string ): Awaitable<NightwatchAPI, NightwatchEnsureResult>; /** * Creates a condition that will wait for the given element's text to equal the given text. */ elementTextIs( element: WebElement | Element | string, text: string ): Awaitable<NightwatchAPI, NightwatchEnsureResult>; /** * Creates a condition that will wait for the given element's text to match a given regular expression. */ elementTextMatches( element: WebElement | Element | string, regex: RegExp ): Awaitable<NightwatchAPI, NightwatchEnsureResult>; /** * Creates a condition that will loop until at least one element is found with the given locator. */ elementsLocated( locator: SeleniumBy ): Awaitable<NightwatchAPI, NightwatchEnsureResult>; /** * 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. */ stalenessOf( element: WebElement | Element | string ): Awaitable<NightwatchAPI, NightwatchEnsureResult>; /** * Creates a condition that will wait for the current page's title to contain the given substring. */ titleContains( substr: string ): Awaitable<NightwatchAPI, NightwatchEnsureResult>; /** * Creates a condition that will wait for the current page's title to match the given value. */ titleIs(title: string): Awaitable<NightwatchAPI, NightwatchEnsureResult>; /** * Creates a condition that will wait for the current page's title to match the given regular expression. */ titleMatches(regex: RegExp): Awaitable<NightwatchAPI, NightwatchEnsureResult>; /** * Creates a condition that will wait for the current page's url to contain the given substring. */ urlContains( substrUrl: string ): Awaitable<NightwatchAPI, NightwatchEnsureResult>; /** * Creates a condition that will wait for the current page's url to match the given value. */ urlIs(url: string): Awaitable<NightwatchAPI, NightwatchEnsureResult>; /** * Creates a condition that will wait for the current page's url to match the given regular expression. */ urlMatches(regex: RegExp): Awaitable<NightwatchAPI, NightwatchEnsureResult>; } export interface ElementProperties { /** * the element selector name * * @example * '@searchBar' */ selector: string; /** * locator strategy can be one of * - css selector * - link text * - partial link text * - tag name * - xpath * * @example * 'css selector' */ locateStrategy?: LocateStrategy; /** * used to target a specific element in a query that results in multiple elements returned. Normally, * only the first element is used (index = 0) but using the index property, you can specify any element within the result. */ index?: number; /** * used to overwrite this setting when using waitForElement* commands. */ abortOnFailure?: boolean; /** * used to overwrite the default timeout for when using waitForElement* commands or assertions. */ timeout?: number; /** * used to overwrite the default retry interval for when using waitForElement* commands or assertions. */ retryInterval?: number; /** * Some element commands like .click() or .getText() will throw a NoSuchElement error if the element cannot be located, causing the test to fail. * If this option is set to true then this error is ignored. */ suppressNotFoundErrors?: boolean; } export interface NightwatchTypedCallbackResult<T> { status: 0; value: T; error: Error; } export interface NightwatchCallbackResultError { status: 1; // we cannot use `number` so giving it a "symbolic" value allows to disjoint the union value: { message: string; screen: string; class: string; stackTrace: Array<{ fileName: string; lineNumber: number; className: string; methodName: string; }>; }; state: Error | string; } export type NightwatchCallbackResult<T> = | NightwatchTypedCallbackResult<T> | NightwatchCallbackResultError; export interface NightwatchLogEntry { /** * The log entry message. */ message: string; /** * The time stamp of log entry in seconds. */ timestamp: number; /** * The log type. */ type: string; /** * Severity level */ level: Level } export interface Level { /** * the level's name. */ name: 'ALL' | 'DEBUG' | 'FINE' | 'FINER' | 'FINEST' | 'INFO' | 'OFF' | 'SEVERE' | 'WARNING'; /** * the level's numeric value. */ value: number; } export interface NightwatchKeys { /** Releases all held modifier keys. */ NULL: string; /** OS-specific keystroke sequence that performs a cancel action. */ CANCEL: string; /** The help key. This key only appears on older Apple keyboards in place of the Insert key. */ HELP: string; /** The backspace key. */ BACK_SPACE: string; /** The tab key. */ TAB: string; /** The clear key. This key only appears on full-size Apple keyboards in place of Num Lock key. */ CLEAR: string; /** The return key. */ RETURN: string; /** The enter (numpad) key. */ ENTER: string; /** The shift key. */ SHIFT: string; /** The control key. */ CONTROL: string; /** The alt key. */ ALT: string; /** The pause key. */ PAUSE: string; /** The escape key. */ ESCAPE: string; /** The space bar. */ SPACE: string; /** The page up key. */ PAGEUP: string; /** The page down key. */ PAGEDOWN: string; /** The end key. */ END: string; /** The home key. */ HOME: string; /** The left arrow. */ ARROW_LEFT: string; LEFT_ARROW: string; /** The up arrow. */ ARROW_UP: string; UP_ARROW: string; /** The right arrow. */ ARROW_RIGHT: string; RIGHT_ARROW: string; /** The down arrow. */ ARROW_DOWN: string; DOWN_ARROW: string; /** The insert key. */ INSERT: string; /** The delete key. */ DELETE: string; /** The semicolon key. */ SEMICOLON: string; /** The equals key. */ EQUALS: string; /** The numpad zero key. */ NUMPAD0: string; /** The numpad one key. */ NUMPAD1: string; /** The numpad two key. */ NUMPAD2: string; /** The numpad three key. */ NUMPAD3: string; /** The numpad four key. */ NUMPAD4: string; /** The numpad five key. */ NUMPAD5: string; /** The numpad six key. */ NUMPAD6: string; /** The numpad seven key. */ NUMPAD7: string; /** The numpad eight key. */ NUMPAD8: string; /** The numpad nine key. */ NUMPAD9: string; /** The numpad multiply (*) key. */ MULTIPLY: string; /** The numpad add (+) key. */ ADD: string; /** The numpad separator (=) key. */ SEPARATOR: string; /** The numpad subtract (-) key. */ SUBTRACT: string; /** The numpad decimal (.) key. */ DECIMAL: string; /** The numpad divide (/) key. */ DIVIDE: string; /** The F1 key. */ F1: string; /** The F2 key. */ F2: string; /** The F3 key. */ F3: string; /** The F4 key. */ F4: string; /** The F5 key. */ F5: string; /** The F6 key. */ F6: string; /** The F7 key. */ F7: string; /** The F8 key. */ F8: string; /** The F9 key. */ F9: string; /** The F10 key. */ F10: string; /** The F11 key. */ F11: string; /** The F12 key. */ F12: string; /** The meta (Windows) key. */ META: string; /** The command (⌘) key. */ COMMAND: string; } /** * Kept for backward compatibility. * * NightwatchPage provides some basic types for page objects. * Users can keep using these default types for page objects, but if they want * to be strict, they can define their own page object types by extending * `NightwatchCustomPageObjects` interface. * * @example * // using default types * const googlePage = browser.page.google(); * * // defining types by extending NightwatchCustomPageObjects interface * interface GooglePage * extends EnhancedPageObject< * typeof googleCommands, * typeof googlePage.elements * > {} * * declare module 'nightwatch' { * interface NightwatchCustomPageObjects { * google(): GooglePage; * } * } * * const googlePage = browser.page.google(); // type automatically inferred as GooglePage */ export type NightwatchPage = { [name: string]: () => EnhancedPageObject<any, any, any>; } & { [name: string]: NightwatchPage; }; export interface NamespacedApi<ReturnType = unknown> { appium: AppiumCommands<ReturnType>; cookies: CookiesNsCommands<ReturnType>; alerts: AlertsNsCommands<ReturnType>; document: DocumentNsCommands<ReturnType>; logs: LogsNsCommands<ReturnType>; window: WindowNsCommands<ReturnType>; firefox: FirefoxNsCommands<ReturnType>; chrome: ChromeNsCommands<ReturnType>; network: NetworkNsCommands<ReturnType>; assert: Assert<ReturnType>; verify: Assert<ReturnType>; expect: Expect; } export interface NightwatchApiCommands { readonly WEBDRIVER_ELEMENT_ID: string; readonly browserName: string; readonly platformName: string; __isBrowserName(browser: string, alternateName: string): boolean; __isPlatformName(platform: string): boolean; isIOS(): boolean; isAndroid(): boolean; isMobile(): boolean; isSafari(): boolean; isChrome(): boolean; isFirefox(): boolean; isEdge(): boolean; isInternetExplorer(): boolean; isOpera(): boolean; /** * Whether or not Nightwatch is being used to connect to an Appium server. */ isAppiumClient(): boolean; } export interface NightwatchAPI extends SharedCommands, WebDriverProtocol, NightwatchCustomCommands, NightwatchApiCommands, NamespacedApi<NightwatchAPI> { baseUrl: string; actions(options?: { async?: boolean; bridge?: boolean }): Actions; ensure: Ensure; page: NightwatchPage & NightwatchCustomPageObjects; /** * SessionId of the session used by the Nightwatch api. */ sessionId: string; /** * Override the sessionId used by Nightwatch client with another session id. */ setSessionId(sessionId: string): this; options: NightwatchTestOptions; Keys: NightwatchKeys; currentTest: NightwatchTestSuite; globals: NightwatchGlobals; /** * https://www.selenium.dev/selenium/docs/api/javascript/WebDriver.html */ driver: WebDriver; launchUrl: string; launch_url: string; } // tslint:disable-next-line:no-empty-interface export interface NightwatchCustomPageObjects { } /** * @deprecated Use `NightwatchAPI` instead. */ export interface NightwatchBrowser extends NightwatchAPI, NightwatchComponentTestingCommands, NightwatchCustomCommands { } /** * @deprecated Please use the types exported by individual plugins. */ export interface NightwatchComponentTestingCommands { /** * @deprecated Please use the types exported by individual plugins. */ importScript( scriptPath: string, options: { scriptType: string; componentType: string }, callback: () => void ): this; /** * @deprecated Please use the types exported by individual plugins. */ mountReactComponent( componentPath: string, props?: string | (() => void), callback?: () => void ): Element; /** * @deprecated Please use the types exported by individual plugins. */ mountComponent( componentPath: string, props?: string | (() => void), callback?: () => void ): Element; /** * @deprecated Please use the types exported by individual plugins. */ mountVueComponent( componentPath: string, options?: any, callback?: () => void ): Element; /** * @deprecated Please use the types exported by individual plugins. */ launchComponentRenderer(): this; } // tslint:disable-next-line export interface NightwatchElement extends WebElement { } export type NightwatchTest = (browser?: NightwatchBrowser) => void; export interface NightwatchTestFunctions { before?: NightwatchTestHook; after?: NightwatchTestHook; beforeEach?: NightwatchTestHook; afterEach?: NightwatchTestHook; '@tags'?: string | string[]; '@disabled'?: boolean; [key: string]: any; } export type NightwatchTestHook = ( browser: NightwatchBrowser, done: (err?: unknown) => void ) => void; export class Element { name: string | undefined; locateStrategy: LocateStrategy; index: number; selector: string | undefined; // and probably `RelativeBy`. pseudoSelector: string | null; resolvedElement: string | null; parent: any; usingRecursion: boolean; webElement?: WebElement; webElementId?: string; abortOnFailure?: boolean; suppressNotFoundErrors?: boolean; retryInterval?: number; message?: string; timeout?: number; } type ElementGlobalDefinition = string | SeleniumBy | RelativeBy | { selector: string; locateStrategy?: string } | { using: string, value: string }; export interface ElementGlobal extends Element { /** * Get the server-assigned opaque ID assigned to this element. */ getId( callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void ): Awaitable<NightwatchAPI, string>; /** * Locates the descendants of this element that match the given search criteria, and returns the first one. * * If no `selector` is passed, returns the [WebElement](https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html) * instance for this element. */ findElement(): Awaitable<NightwatchAPI, WebElement>; findElement( selector: ElementGlobalDefinition, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<WebElement>) => void ): Awaitable<NightwatchAPI, WebElement>; /** * Locates and wraps the first element, that match the given search criteria in the descendants of this element, in global element() api object. * * If no `selector` is passed, returns the [WebElement](https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html) * instance for this element. */ find(): Awaitable<NightwatchAPI, WebElement>; find( selector: ElementGlobalDefinition, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<ElementGlobal | null>) => void ): Awaitable<NightwatchAPI, ElementGlobal | null>; get: ElementGlobal['find']; element: ElementGlobal['find']; /** * Locates all of the descendants of this element that match the given search criteria. */ findElements( selector: ElementGlobalDefinition, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<WebElement[]>) => void ): Awaitable<NightwatchAPI, WebElement[]>; findAll( selector: ElementGlobalDefinition, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<ElementGlobal[]>) => void ): Awaitable<NightwatchAPI, ElementGlobal[]>; /** * Clear the `value` of this element. This command has no effect if the underlying DOM element * is neither a text INPUT element nor a TEXTAREA element. * * @see https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html#clear */ clear( callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<null>) => void ): Awaitable<NightwatchAPI, null>; /** * Clicks on this element. * * @see https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html#click */ click( callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<null>) => void ): Awaitable<NightwatchAPI, null>; /** * Get the computed WAI-ARIA label of element. */ getAccessibleName( callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void ): Awaitable<NightwatchAPI, string>; /** * Get the computed WAI-ARIA label of element. */ accessibleName: ElementGlobal['getAccessibleName']; /** * Get the computed WAI-ARIA role of element. */ getAriaRole( callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void ): Awaitable<NightwatchAPI, string>; /** * Get the computed WAI-ARIA role of element. */ ariaRole: ElementGlobal['getAriaRole']; /** * Retrieves the current value of the given attribute of this element. * * @see https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html#getAttribute */ getAttribute( attributeName: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string | null>) => void ): Awaitable<NightwatchAPI, string | null>; /** * Retrieves the current value of the given attribute of this element. * * @see https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html#getAttribute */ attr: ElementGlobal['getAttribute']; /** * Retrieves the current value of the given attribute of this element. * * @see https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html#getAttribute */ attribute: ElementGlobal['getAttribute']; /** * Retrieves the value of a computed style property for this instance. * * @see https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html#getCssValue */ getCssValue( cssStyleProperty: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void ): Awaitable<NightwatchAPI, string>; /** * Retrieves the value of a computed style property for this instance. * * @see https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html#getCssValue */ css: ElementGlobal['getCssValue']; /** * Retrieves the value of the given property of this element. */ getProperty( propertyName: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string | null>) => void ): Awaitable<NightwatchAPI, string | null>; /** * Retrieves the value of the given property of this element. */ property: ElementGlobal['getProperty']; /** * Retrieves the value of the given property of this element. */ prop: ElementGlobal['getProperty']; /** * Returns an object describing an element's location, in pixels relative to the document element, and the element's size in pixels. */ getRect( callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchSizeAndPosition>) => void ): Awaitable<NightwatchAPI, NightwatchSizeAndPosition>; /** * Returns an object describing an element's location, in pixels relative to the document element, and the element's size in pixels. */ rect: ElementGlobal['getRect']; /** * Retrieves the element's tag name. */ getTagName( callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void ): Awaitable<NightwatchAPI, string>; /** * Retrieves the element's tag name. */ tagName: ElementGlobal['getTagName']; /** * Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace. */ getText( callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void ): Awaitable<NightwatchAPI, string>; /** * Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace. */ text: ElementGlobal['getText']; /** * Types a key sequence on the DOM element represented by this instance. * * @example * element(<selector>).sendKeys(1, 'something', browser.Keys.SPACE, Promise.resolve(2)); * * @see https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html#sendKeys */ sendKeys( ...args: Array<string | number | PromiseLike<string> | PromiseLike<number>> ): Awaitable<NightwatchAPI, null>; /** * Submits the form containing this element (or this element if it is itself a FORM element). * This command is a no-op if the element is not contained in a form. * * @see https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html#submit */ submit( callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<null>) => void ): Awaitable<NightwatchAPI, null>; /** * Take a screenshot of the visible region encompassed by this element's bounding rectangle. */ takeScreenshot( callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void ): Awaitable<NightwatchAPI, string>; /** * Take a screenshot of the visible region encompassed by this element's bounding rectangle. */ screenshot: ElementGlobal['takeScreenshot']; /** * Test whether this element is currently displayed. */ isDisplayed( callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<boolean>) => void ): Awaitable<NightwatchAPI, boolean>; /** * Tests whether this element is enabled, as dictated by the `disabled` attribute. */ isEnabled( callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<boolean>) => void ): Awaitable<NightwatchAPI, boolean>; /** * Tests whether this element is selected. */ isSelected( callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<boolean>) => void ): Awaitable<NightwatchAPI, boolean>; /** * Get the [WebElement](https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html) instance for this element. */ getWebElement(): Awaitable<NightwatchAPI, WebElement>; isComponent?: boolean; } export function globalElement( locator: Definition, options?: { isComponent?: boolean; type: string; } ): ElementGlobal; export type NightwatchTests = NightwatchTestFunctions; export class DescribeInstance { '[instance]': any; '[attributes]': {}; '[client]': NightwatchClient; /** * Title of the describe suite. */ get name(): string; /** * Get or set tags for the test suite. * * @see https://nightwatchjs.org/guide/running-tests/filtering-by-test-tags.html */ get tags(): string | string[]; set tags(value: string | string[]); /** * Enable if the current test is a unit/integration test * (no webdriver session is required). */ get unitTest(): boolean; set unitTest(value: boolean); /** * Set to false if you'd like the browser window to be kept open * in case of a failure or error (useful for debugging). */ get endSessionOnFail(): boolean; set endSessionOnFail(value: boolean); /** * Set to false if you'd like the rest of the test cases/test steps * to be executed in the event of an assertion failure/error. */ get skipTestcasesOnFail(): boolean; set skipTestcasesOnFail(value: boolean); /** * Set to true if you'd like this test suite to be skipped by the * test runner. */ get disabled(): boolean; set disabled(value: boolean); /** * Get or set testsuite specific capabilities. */ get desiredCapabilities(): NightwatchDesiredCapabilities; set desiredCapabilities(value: NightwatchDesiredCapabilities); /** * Get available page objects. */ get page(): NightwatchAPI['page']; /** * Get all current globals. */ get globals(): NightwatchGlobals; /** * Get all current settings. */ get settings(): NightwatchOptions; /** * Get all current cli arguments. */ get argv(): { [key: string]: any }; /** * Get all current mocha options. */ get mochaOptions(): { [key: string]: any } | undefined; /** * Control the unit test timeout. * * Control the assertion and element commands timeout until when * an element should be located or assertion passed. * * @param value Timeout in `ms` */ timeout(value: number): void; /** * Get the assertion and element commands timeout until when * an element would be located or assertion passed. * * @returns Timeout in `ms` */ waitForTimeout(): number; /** * Control the assertion and element commands timeout until when * an element should be located or assertion passed. * * @param value Timeout in `ms` */ waitForTimeout(value: number): void; /** * Get the polling interval between re-tries for assertions * or element commands. * * @returns Time interval in `ms` */ waitForRetryInterval(): number; /** * Control the polling interval between re-tries for assertions * or element commands. * * @param value Time interval in `ms` */ waitForRetryInterval(value: number): void; /** * Control the polling interval between re-tries for assertions * or element commands. * * @param value Time interval in `ms` */ retryInterval(value: number): void; /** * How many time to retry a failed testcase inside this test suite */ retries(n: number): void; /** * How many times to retry the current test suite in case of an * assertion failure or error */ suiteRetries(n: number): void; } export type ExtendDescribeThis<T> = DescribeInstance & { [P in keyof T]?: T[P]; }; interface SuiteFunction { (title: string, fn?: (this: DescribeInstance) => void): this; only: ExclusiveSuiteFunction; skip: PendingSuiteFunction; } interface ExclusiveSuiteFunction { (title: string, fn?: (this: DescribeInstance) => void): this; } interface PendingSuiteFunction { (title: string, fn?: (this: DescribeInstance) => void): this | void; } interface ExclusiveTestFunction { (fn: NormalFunc | AsyncFunc): this; (title: string, fn: NormalFunc | AsyncFunc): this; } interface PendingTestFunction { (fn: NormalFunc | AsyncFunc): this; (title: string, fn: NormalFunc | AsyncFunc): this; } type NormalFunc = (this: DescribeInstance, browser: NightwatchBrowser) => void; type AsyncFunc = ( this: DescribeInstance, browser: NightwatchBrowser ) => PromiseLike<any>; interface TestFunction { (fn: NormalFunc | AsyncFunc): this; (title: string, fn: NormalFunc | AsyncFunc): this; only: ExclusiveTestFunction; skip: PendingTestFunction; retries(n: number): void; } type NightwatchBddTestHookCallback = ( this: DescribeInstance, browser: NightwatchBrowser, done: (err?: any) => void ) => void; type NightwatchBddTestHook = (callback: NightwatchBddTestHookCallback) => void; declare global { const describe: SuiteFunction; const xdescribe: PendingSuiteFunction; const context: SuiteFunction; const xcontext: PendingSuiteFunction; const test: TestFunction; const it: TestFunction; const xit: PendingTestFunction; const specify: TestFunction; const xspecify: PendingTestFunction; const before: NightwatchBddTestHook; const after: NightwatchBddTestHook; const beforeEach: NightwatchBddTestHook; const afterEach: NightwatchBddTestHook; } export interface NightwatchClient extends NightwatchClientObject { argv: { [key: string]: any }; client: NightwatchClientObject; configLocateStrategy: "css selector" | "xpath"; // TODO: Add missing properties, like: // elementLocator // httpOpts // initialCapabilities // queue // reporter unitTestingMode: boolean; usingCucumber: boolean; } export interface NightwatchClientObject { api: NightwatchAPI; options: NightwatchOptions; settings: NightwatchOptions; locateStrategy: LocateStrategy; // TODO: Add missing properties, like: // reporter: reporter // elementLocator sessionId: string | null; } export interface HttpRequestOptions { /** * The pathname of the endpoint to call. Ex: `'/session/:sessionId/url'`. * * Alternatively, url property could be provided with the full URL. */ path?: string; data?: unknown; /** * For custom-commands, set to `this.api.sessionId`. */ sessionId: string; method: 'POST' | 'GET' | 'DELETE' | 'PUT'; use_ssl?: boolean; host?: string; port?: number; /** * The full URL to call. Ex: `http://localhost:4444/session/:sessionId/url`. */ url?: string; auth?: { user: string; pass: string; } } export interface CommandInstance { get api(): NightwatchAPI; get client(): NightwatchClient; get commandArgs(): unknown[]; get commandFileName(): string; get driver(): WebDriver; get isES6AsyncCommand(): boolean; get reuseBrowser(): boolean; /** * Direct access to methods present in the `lib/transport/selenium-webdriver/method-mappings.js` file * of Nightwatch code. * * TODO: complete the type definition. * * For now, you would need to create custom interface to use this property, like below: * ```ts * interface TransportActions { * getCurrentUrl(): Promise<NightwatchCallbackResult<string>>; * } * ``` * then use it inside your custom command like: * ```ts * const currentUrl = await (this.transportActions as TransportActions).getCurrentUrl(); * ``` */ get transportActions(): unknown; /** * Directly call the HTTP endpoints of the Selenium/WebDriver server. * * This is useful when you need to call a command that is not directly supported by Nightwatch API. * * @see https://nightwatchjs.org/guide/extending-nightwatch/adding-custom-commands.html#postdoc-directly-calling-seleniumwebdriver-endpoints */ httpRequest(options: HttpRequestOptions): Promise<unknown>; toString(): string; complete(...args: unknown[]): void; } export interface CreateClientParams { browserName?: string | null; headless?: boolean; silent?: boolean; output?: boolean; useAsync?: boolean; env?: string | null; timeout?: number | null; parallel?: boolean; reporter?: any; globals?: Partial<NightwatchGlobals>; devtools?: boolean; debug?: boolean; enable_global_apis?: boolean; config?: string; test_settings?: Partial<NightwatchOptions>; } export interface Nightwatch { /** * Internal method in Nightwatch. */ cli(callback: () => void): void; /** * Internal method in Nightwatch. */ client(settings: NightwatchOptions, reporter?: any, argv?: {}, skipInt?: boolean): this; /** * Internal method in Nightwatch. */ CliRunner(argv?: {}): this; // TODO: return type is `CliRunner` instance. /** * Internal method in Nightwatch. */ initClient(opts?: {}): this; /** * Internal method in Nightwatch. * * @deprecated */ runner(argv?: {}, done?: () => void, settings?: {}): Promise<void>; /** * Internal method in Nightwatch. */ runTests(testSource: string | string[], settings?: any, ...args: any[]): Promise<void>; /** * Creates a new Nightwatch client that can be used to create WebDriver sessions. * * @example * const Nightwatch = require('nightwatch'); * * const client = Nightwatch.createClient({ * headless: true, * output: true, * silent: true, // set to false to enable verbose logging * browserName: 'firefox', // can be either: firefox, chrome, safari, or edge * * // set the global timeout to be used with waitFor commands and when retrying assertions/expects * timeout: 10000, * * // set the current test environment from the nightwatch config * env: null, * * // any additional capabilities needed * desiredCapabilities: { * * }, * * // can define/overwrite test globals here; * // when using a third-party test runner only the global hooks onBrowserNavigate/onBrowserQuit are supported * globals: {}, * * // when the test runner used supports running tests in parallel; * // set to true if you need the webdriver port to be randomly generated * parallel: false, * * // All other Nightwatch config settings can be overwritten here, such as: * disable_colors: false * }); * * @see https://nightwatchjs.org/api/programmatic/#programmatic-api */ createClient({ headless, silent, output, useAsync, env, timeout, parallel, reporter, browserName, globals, devtools, debug, enable_global_apis, config, test_settings }?: CreateClientParams): NightwatchProgrammaticAPIClient; // TODO: add the following missing properties // Logger // element (only available after createClient is called) // Not adding named-exports (Namespaced API) here because those // would go away from Nightwatch interface after migrating to TypeScript, // because then named-exports will be exported directly instead // of first adding them to Nightwatch (default export). browser: NightwatchAPI; app: NightwatchAPI; by: typeof SeleniumBy; Capabilities: typeof Capabilities; Key: NightwatchKeys; } export interface NightwatchProgrammaticAPIClient { /** * Create a new browser session. * * Returns [NightwatchAPI](https://nightwatchjs.org/api/) object. * * @example * const browser = await client.launchBrowser(); */ launchBrowser(): Promise<NightwatchAPI>; /** * Update the initially specified capabilities. * * @example * client.updateCapabilities({ * testCapability: 'one, two, three' * }); */ updateCapabilities(value: {} | (() => {})): void; nightwatch_client: NightwatchClient; settings: NightwatchOptions; // TODO: 'transport' property missing } export type LocateStrategy = | 'class name' | 'css selector' | 'id' | 'name' | 'link text' | 'partial link text' | 'tag name' | 'xpath' // Appium-specific strategies | 'accessibility id' | '-android uiautomator' | '-ios predicate string' | '-ios class chain'; export type NightwatchLogTypes = | 'client' | 'driver' | 'browser' | 'server' | 'performance'; export interface SharedCommands extends ClientCommands, ElementCommands { } export interface WindowPosition { x: number; y: number; } // tslint:disable-next-line export interface NightwatchPosition extends WindowPosition { } export interface WindowSize { height: number; width: number; } // tslint:disable-next-line export interface NightwatchSize extends WindowSize { } export type WindowSizeAndPosition = WindowPosition & WindowSize; export type NightwatchSizeAndPosition = WindowSizeAndPosition; export type WindowType = 'tab' | 'window'; export interface ChromiumClientCommands { /** * Mock the geolocation of the browser. * * Call without any arguments to reset the geolocation. * * @example * describe('mock geolocation', function() { * it('sets the geolocation to Tokyo, Japan and then resets it', () => { * browser * .setGeolocation({ * latitude: 35.689487, * longitude: 139.691706, * accuracy: 100 * }) // sets the geolocation to Tokyo, Japan * .navigateTo('https://www.gps-coordinates.net/my-location') * .pause(3000) * .setGeolocation() // resets the geolocation * .navigateTo('https://www.gps-coordinates.net/my-location') * .pause(3000); * }); * }); * * @see https://nightwatchjs.org/guide/network-requests/mock-geolocation.html */ setGeolocation( coordinates?: { latitude: number; longitude: number; accuracy?: number }, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; /** * Override device mode/dimensions. * * @example * describe('modify device dimensions', function() { * it('modifies the device dimensions and then resets it', function() { * browser * .setDeviceDimensions({ * width: 400, * height: 600, * deviceScaleFactor: 50, * mobile: true * }) * .navigateTo('https://www.google.com') * .pause(1000) * .setDeviceDimensions() // resets the device dimensions * .navigateTo('https://www.google.com') * .pause(1000); * }); * }); * * @see https://nightwatchjs.org/guide/mobile-web-testing/override-device-dimensions.html */ setDeviceDimensions( metrics?: { width?: number; height?: number; deviceScaleFactor?: number; mobile?: boolean; }, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; /** * Get the performance metrics from the browser. Metrics collection * only begin after `enablePerformanceMetrics()` command is called. * * @returns A promise that contains metrics collected between the * last call to `enablePerformanceMetrics()` command and this command. * * @example * describe('collect performance metrics', function() { * it('enables the metrics collection, does some stuff and collects the metrics', function() { * browser * .enablePerformanceMetrics() * .navigateTo('https://www.google.com') * .getPerformanceMetrics((result) => { * if (result.status === 0) { * const metrics = result.value; * console.log(metrics); * } * }); * }); * }); * * @see https://web.dev/metrics/ * @see https://pptr.dev/api/puppeteer.page.metrics/ */ getPerformanceMetrics( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<{ [metricName: string]: number }> ) => void ): Awaitable<this, { [metricName: string]: number }>; /** * Enable/disable the collection of performance metrics in the browser. Metrics * collection only begin after this command is called. * * @example * describe('collect performance metrics', function() { * it('enables the metrics collection, does some stuff and collects the metrics', function() { * browser * .enablePerformanceMetrics() * .navigateTo('https://www.google.com') * .getPerformanceMetrics((result) => { * if (result.status === 0) { * const metrics = result.value; * console.log(metrics); * } * }); * }); * }); * * @see https://web.dev/metrics/ * @see https://pptr.dev/api/puppeteer.page.metrics/ */ enablePerformanceMetrics( enable?: boolean, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; /** * Take heap snapshot and save it as a `.heapsnapshot` file. * The saved snapshot file can then be loaded into Chrome * DevTools' Memory tab for inspection. * * The contents of the heap snapshot are also available in the `value` * property of the `result` argument passed to the callback, in * string-serialized JSON format. * * @returns A promise that contains heap snapshot in string-serialized * JSON format. * * @example * describe('take heap snapshot', function() { * it('takes heap snapshot and saves it as snap.heapsnapshot file', function() { * browser * .navigateTo('https://www.google.com') * .takeHeapSnapshot('./snap.heapsnapshot'); * }); * }); * * @see https://nightwatchjs.org/guide/running-tests/take-heap-snapshot.html */ takeHeapSnapshot( heapSnapshotLocation?: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>; captureNetworkRequests: NetworkNsCommands<this>['captureRequests']; mockNetworkResponse: NetworkNsCommands<this>['mockResponse']; setNetworkConditions: NetworkNsCommands<this>['setConditions']; captureBrowserConsoleLogs: LogsNsCommands<this>['captureBrowserConsoleLogs']; captureBrowserExceptions: LogsNsCommands<this>['captureBrowserExceptions']; } export interface ClientCommands extends ChromiumClientCommands { /** * Close the current window. This can be useful when you're working with multiple windows open (e.g. an OAuth login). * Uses `window` protocol command. * * @example * describe('closeWindow command demo' , function (result) { * test('demo test', function () { * browser.closeWindow(); * }); * }); * @see https://nightwatchjs.org/api/closeWindow.html * * @deprecated In favour of `.window.close()`. */ closeWindow( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; /** * Sets the current window state to fullscreen. * * @example * module.exports = { * 'demo Test': function(browser) { * browser.fullscreenWindow(function(result) { * console.log(result); * }); * }, * * 'ES6 async demo Test': async function(browser) { * const result = await browser.fullscreenWindow(); * console.log('result value is:', result.value); * } * } * @see https://nightwatchjs.org/api/fullscreenWindow.html * * @deprecated In favour of `.window.fullscreen()`. */ fullscreenWindow( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; /** * Hides the window in the system tray. If the window happens to be in fullscreen mode, * it is restored the normal state then it will be "iconified" - minimize or hide the window from the visible screen. * * @example * module.exports = { * 'demo Test': function(browser) { * browser.minimizeWindow(function(result) { * console.log(result); * }); * }, * * 'ES6 async demo Test': async function(browser) { * const result = await browser.minimizeWindow(); * console.log('result value is:', result.value); * } * } * @see https://nightwatchjs.org/api/minimizeWindow.html * * @deprecated In favour of `.window.minimize()`. */ minimizeWindow( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; /** * Opens a new top-level browser window, which can be either a tab (default) or a separate new window. * * This command is only available for W3C Webdriver compatible browsers. * * @example * module.exports = { * 'demo Test': function(browser) { * // open a new window tab (default) * browser.openNewWindow(function(result) { * console.log(result); * }); * * // open a new window * browser.openNewWindow('window', function(result) { * console.log(result); * }); * }, * * 'ES6 async demo Test': async function(browser) { * const result = await browser.openNewWindow(); * console.log('result value is:', result.value); * } * } * @see https://nightwatchjs.org/api/openNewWindow.html * * @deprecated In favour of `.window.open()`. */ openNewWindow( type?: WindowType, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; /** * Delete the cookie with the given name. This command is a no-op if there is no such cookie visible to the current page. * * @example * this.demoTest = function() { * browser.deleteCookie("test_cookie", function() { * // do something more in here * }); * } * * @see https://nightwatchjs.org/api/deleteCookie.html * * @deprecated In favour of `.cookies.delete()`. */ deleteCookie( cookieName: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; /** * Delete all cookies visible to the current page. * * @example * this.demoTest = function() { * browser.deleteCookies(function() { * // do something more in here * }); * } * * @see https://nightwatchjs.org/api/deleteCookies.html * * @deprecated In favour of `.cookies.deleteAll()`. */ deleteCookies( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; /** * Ends the session. Uses session protocol command. * * @example * this.demoTest = function () { * browser.end(); * }; * * @see https://nightwatchjs.org/api/end.html */ end( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;