nightwatch
- Version 3.12.0
- Published
- 1.92 MB
- 34 dependencies
- MIT license
Install
npm i nightwatch
yarn add nightwatch
pnpm add nightwatch
Overview
Easy to use Node.js based end-to-end testing solution for web applications using the W3C WebDriver API.
Index
Variables
Functions
Classes
Interfaces
ClientCommands
- axeInject()
- axeRun()
- closeWindow()
- debug()
- deleteCookie()
- deleteCookies()
- end()
- fullscreenWindow()
- getCookie()
- getCookies()
- getCurrentUrl()
- getLog()
- getLogTypes()
- getTitle()
- getWindowPosition()
- getWindowRect()
- getWindowSize()
- init()
- injectScript()
- isLogAvailable()
- maximizeWindow()
- minimizeWindow()
- navigateTo()
- openNewWindow()
- pageSource()
- pause()
- perform()
- quit()
- resizeWindow()
- saveScreenshot()
- setCookie()
- setWindowPosition()
- setWindowRect()
- setWindowSize()
- switchToWindow()
- switchWindow()
- urlHash()
- useCss()
- useXpath()
- waitUntil()
ElementCommands
- check()
- clearValue()
- click()
- clickAndHold()
- doubleClick()
- dragAndDrop()
- findElement()
- findElements()
- getAccessibleName()
- getAriaRole()
- getAttribute()
- getCssProperty()
- getElementProperty()
- getElementRect()
- getElementSize()
- getFirstElementChild()
- getLastElementChild()
- getLocation()
- getLocationInView()
- getNextSibling()
- getPreviousSibling()
- getShadowRoot()
- getTagName()
- getText()
- getValue()
- hasDescendants()
- isEnabled()
- isPresent()
- isSelected()
- isVisible()
- moveToElement()
- rightClick()
- sendKeys()
- setAttribute()
- setPassword()
- setValue()
- submitForm()
- takeElementScreenshot()
- uncheck()
- updateValue()
- uploadFile()
- waitForElementNotPresent()
- waitForElementNotVisible()
- waitForElementPresent()
- waitForElementVisible()
ElementGlobal
- accessibleName
- ariaRole
- attr
- attribute
- clear()
- click()
- css
- element
- find()
- findAll()
- findElement()
- findElements()
- get
- getAccessibleName()
- getAriaRole()
- getAttribute()
- getCssValue()
- getId()
- getProperty()
- getRect()
- getTagName()
- getText()
- getWebElement()
- isComponent
- isDisplayed()
- isEnabled()
- isSelected()
- prop
- property
- rect
- screenshot
- sendKeys()
- submit()
- tagName
- takeScreenshot()
- text
Ensure
- ableToSwitchToFrame()
- alertIsPresent()
- elementIsDisabled()
- elementIsEnabled()
- elementIsNotSelected()
- elementIsNotVisible()
- elementIsSelected()
- elementIsVisible()
- elementLocated()
- elementsLocated()
- elementTextContains()
- elementTextIs()
- elementTextMatches()
- stalenessOf()
- titleContains()
- titleIs()
- titleMatches()
- urlContains()
- urlIs()
- urlMatches()
NightwatchCommonAssertions
- attributeContains()
- attributeEquals()
- attributeMatches()
- containsText()
- cssClassNotPresent()
- cssClassPresent()
- cssProperty()
- domPropertyContains()
- domPropertyEquals()
- domPropertyMatches()
- elementNotPresent()
- elementPresent()
- elementsCount()
- enabled()
- hasAttribute()
- hasClass()
- hidden()
- NightwatchAssertionsError
- selected()
- textContains()
- textEquals()
- textMatches()
- title()
- titleContains()
- titleEquals()
- titleMatches()
- urlContains()
- urlEquals()
- urlMatches()
- value()
- valueContains()
- valueEquals()
- visible()
NightwatchDesiredCapabilities
- 'goog:chromeOptions'
- 'goog:loggingPrefs'
- acceptInsecureCerts
- acceptSslCerts
- applicationCacheEnabled
- browserConnectionEnabled
- browserName
- browserVersion
- chromeOptions
- cssSelectorsEnabled
- databaseEnabled
- elementScrollBehaviour
- handlesAlerts
- javascriptEnabled
- locationContextEnabled
- nativeEvents
- platformName
- rotatable
- takesScreenShot
- unexpectedAlertBehaviour
- webStorageEnabled
NightwatchInternalGlobals
- abortOnAssertionFailure
- abortOnElementLocateError
- after()
- afterEach()
- asyncHookTimeout
- before()
- beforeEach()
- customReporterCallbackTimeout
- onBrowserNavigate()
- onBrowserQuit()
- reporter()
- retryAssertionTimeout
- reuseBrowserSession
- suppressWarningsOnMultipleElementsReturned
- throwOnMultipleElementsReturned
- unitTestsTimeout
- waitForConditionPollInterval
- waitForConditionTimeout
NightwatchKeys
- ADD
- ALT
- ARROW_DOWN
- ARROW_LEFT
- ARROW_RIGHT
- ARROW_UP
- BACK_SPACE
- CANCEL
- CLEAR
- COMMAND
- CONTROL
- DECIMAL
- DELETE
- DIVIDE
- DOWN_ARROW
- END
- ENTER
- EQUALS
- ESCAPE
- F1
- F10
- F11
- F12
- F2
- F3
- F4
- F5
- F6
- F7
- F8
- F9
- HELP
- HOME
- INSERT
- LEFT_ARROW
- META
- MULTIPLY
- NULL
- NUMPAD0
- NUMPAD1
- NUMPAD2
- NUMPAD3
- NUMPAD4
- NUMPAD5
- NUMPAD6
- NUMPAD7
- NUMPAD8
- NUMPAD9
- PAGEDOWN
- PAGEUP
- PAUSE
- RETURN
- RIGHT_ARROW
- SEMICOLON
- SEPARATOR
- SHIFT
- SPACE
- SUBTRACT
- TAB
- UP_ARROW
NightwatchOptions
- always_async_commands
- backwards_compatibility_mode
- custom_assertions_path
- custom_commands_path
- default_reporter
- disable_global_apis
- disable_global_expect
- disable_typescript
- dotenv
- element_command_retries
- globals_path
- page_objects_path
- parallel_mode
- plugins
- report_command_errors
- report_network_errors
- report_prefix
- test_settings
- trace
- tsconfig_path
- usage_analytics
NightwatchTestSettingGeneric
- base_url
- baseUrl
- desiredCapabilities
- detailed_output
- disable_colors
- disable_error_log
- disable_output_boxes
- enable_fail_fast
- end_session_on_fail
- exclude
- filter
- globals
- launch_url
- launchUrl
- live_output
- log_screenshot_data
- output
- output_folder
- output_timestamp
- parallel_process_delay
- persist_globals
- reporter_options
- screenshots
- selenium
- selenium_host
- selenium_port
- silent
- skip_testcases_on_fail
- skipgroup
- skiptags
- src_folders
- start_session
- sync_test_names
- tag_filter
- test_runner
- test_workers
- timestamp_format
- unit_testing_mode
- unit_tests_mode
- use_child_process
- use_ssl
- use_xpath
- webdriver
- window_size
ScopedElement
- accessibleName()
- ariaRole()
- assert
- attr()
- attribute()
- check()
- clear()
- click()
- clickAndHold()
- css()
- doubleClick()
- dragAndDrop()
- find()
- findAll()
- findAllByAltText()
- findAllByPlaceholderText()
- findAllByRole()
- findAllByText()
- findByAltText()
- findByLabelText()
- findByPlaceholderText()
- findByRole()
- findByText()
- findElement()
- findElements()
- get()
- getAccessibleName()
- getAll()
- getAllByRole()
- getAriaRole()
- getAttribute()
- getComputedLabel()
- getComputedRole()
- getCssProperty()
- getCssValue()
- getFirstElementChild()
- getId()
- getLastElementChild()
- getLocation()
- getNextElementSibling()
- getPreviousElementSibling()
- getProperty()
- getRect()
- getShadowRoot()
- getSize()
- getTagName()
- getText()
- getValue()
- isActive()
- isDisplayed()
- isEnabled()
- isPresent()
- isSelected()
- isVisible()
- moveTo()
- prop()
- property()
- rect()
- rightClick()
- sendKeys()
- setAttribute()
- setProperty()
- setValue()
- submit()
- tagName()
- takeScreenshot()
- text()
- uncheck()
- update()
- upload()
- waitUntil()
- webElement
WebdriverOptions
- access_key
- android_chrome
- check_process_delay
- chrome_binary
- chrome_log_file
- cli_args
- default_path_prefix
- edge_binary
- edge_log_file
- firefox_binary
- firefox_profile
- host
- internal_server_error_retry_interval
- keep_alive
- log_file_name
- log_path
- max_status_poll_tries
- port
- process_create_timeout
- proxy
- server_path
- ssl
- start_process
- status_poll_interval
- timeout_options
- use_legacy_jsonwire
- username
Type Aliases
- Awaitable
- Definition
- DragAndDropDestination
- ElementAssertionsOptions
- ElementsAssertionsOptions
- EnhancedPageObject
- EnhancedSectionInstance
- ExtendDescribeThis
- KeysFilter
- LocateStrategy
- NightwatchAssert
- NightwatchCallbackResult
- NightwatchGenericCallback
- NightwatchLogTypes
- NightwatchPage
- NightwatchSizeAndPosition
- NightwatchTest
- NightwatchTestHook
- NightwatchTests
- ScopedElementRect
- ScopedElementSelector
- ScopedSelector
- ScopedSelectorObject
- ValueAssertionsOptions
- WaitUntilActions
- WaitUntilOptions
- WindowSizeAndPosition
- WindowType
Namespaces
Variables
variable _default
const _default: Nightwatch;
variable alerts
const alerts: AlertsNsCommands<unknown>;
variable app
const app: NightwatchAPI;
variable appium
const appium: AppiumCommands<unknown>;
variable assert
const assert: Assert<unknown>;
variable browser
const browser: NightwatchAPI;
variable chrome
const chrome: ChromeNsCommands<unknown>;
variable cookies
const cookies: CookiesNsCommands<unknown>;
variable document
const document: DocumentNsCommands<unknown>;
variable element
const element: ElementFunction;
variable ELEMENT_KEY
const ELEMENT_KEY: string;
variable expect
const expect: Expect;
variable firefox
const firefox: FirefoxNsCommands<unknown>;
variable verify
const verify: Assert<unknown>;
variable window
const window: WindowNsCommands<unknown>;
Functions
function globalElement
globalElement: ( locator: Definition, options?: { isComponent?: boolean; type: string }) => ElementGlobal;
Classes
class DescribeInstance
class DescribeInstance {}
property '[attributes]'
'[attributes]': {};
property '[client]'
'[client]': NightwatchClient;
property '[instance]'
'[instance]': any;
property argv
readonly argv: { [key: string]: any };
Get all current cli arguments.
property desiredCapabilities
desiredCapabilities: NightwatchDesiredCapabilities;
Get or set testsuite specific capabilities.
property disabled
disabled: boolean;
Set to true if you'd like this test suite to be skipped by the test runner.
property endSessionOnFail
endSessionOnFail: 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).
property globals
readonly globals: NightwatchGlobals;
Get all current globals.
property mochaOptions
readonly mochaOptions: { [key: string]: any };
Get all current mocha options.
property name
readonly name: string;
Title of the describe suite.
property page
readonly page: { [name: string]: () => EnhancedPageObject<any, any, any, {}, string>;} & { [name: string]: NightwatchPage } & NightwatchCustomPageObjects;
Get available page objects.
property settings
readonly settings: NightwatchOptions;
Get all current settings.
property skipTestcasesOnFail
skipTestcasesOnFail: 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.
property tags
tags: string | string[];
Get or set tags for the test suite.
See Also
https://nightwatchjs.org/guide/running-tests/filtering-by-test-tags.html
property unitTest
unitTest: boolean;
Enable if the current test is a unit/integration test (no webdriver session is required).
method retries
retries: (n: number) => void;
How many time to retry a failed testcase inside this test suite
method retryInterval
retryInterval: (value: number) => void;
Control the polling interval between re-tries for assertions or element commands.
Parameter value
Time interval in
ms
method suiteRetries
suiteRetries: (n: number) => void;
How many times to retry the current test suite in case of an assertion failure or error
method timeout
timeout: (value: number) => void;
Control the unit test timeout.
Control the assertion and element commands timeout until when an element should be located or assertion passed.
Parameter value
Timeout in
ms
method waitForRetryInterval
waitForRetryInterval: { (): number; (value: number): void };
Get the polling interval between re-tries for assertions or element commands.
Returns
Time interval in
ms
Control the polling interval between re-tries for assertions or element commands.
Parameter value
Time interval in
ms
method waitForTimeout
waitForTimeout: { (): number; (value: number): void };
Get the assertion and element commands timeout until when an element would be located or assertion passed.
Returns
Timeout in
ms
Control the assertion and element commands timeout until when an element should be located or assertion passed.
Parameter value
Timeout in
ms
class Element
class Element {}
property abortOnFailure
abortOnFailure?: boolean;
property index
index: number;
property locateStrategy
locateStrategy: LocateStrategy;
property message
message?: string;
property name
name: string;
property parent
parent: any;
property pseudoSelector
pseudoSelector: string;
property resolvedElement
resolvedElement: string;
property retryInterval
retryInterval?: number;
property selector
selector: string;
property suppressNotFoundErrors
suppressNotFoundErrors?: boolean;
property timeout
timeout?: number;
property usingRecursion
usingRecursion: boolean;
property webElement
webElement?: WebElement;
property webElementId
webElementId?: string;
class ElementAssertions
class ElementAssertions {}
constructor
constructor(element: ScopedElement, options: ElementAssertionsOptions);
property not
readonly not: ElementAssertions;
method enabled
enabled: (message?: string) => Promise<WebElement>;
method hasAttribute
hasAttribute: (name: string, message?: string) => Promise<WebElement>;
method hasClass
hasClass: (name: string, message?: string) => Promise<WebElement>;
method hasDescendants
hasDescendants: (message?: string) => Promise<WebElement>;
method present
present: (message?: string) => Promise<WebElement>;
method selected
selected: (message?: string) => Promise<WebElement>;
method visible
visible: (message?: string) => Promise<WebElement>;
class ElementLocator
class ElementLocator {}
constructor
constructor(selector: any, nightwatchInstance: NightwatchClient);
property abortOnFailure
abortOnFailure: boolean;
property condition
condition: any;
property index
index: number;
property locateStrategy
locateStrategy: LocateStrategy;
property retryInterval
retryInterval: number;
property suppressNotFoundErrors
suppressNotFoundErrors: boolean;
property timeout
timeout: number;
class Elements
class Elements implements PromiseLike<WebElement[]> {}
constructor
constructor( selector: any, parentScopedElement: ScopedElement, nightwatchInstance: NightwatchClient);
method count
count: () => ElementValue<number>;
method nth
nth: (index: number) => ScopedElement;
method then
then: <R1 = WebElement[], R2 = never>( onfulfilled?: (value: WebElement[]) => R1 | PromiseLike<R1>, onrejected?: (reason: any) => R2 | PromiseLike<R2>) => PromiseLike<R1 | R2>;
class ElementsAssertions
class ElementsAssertions {}
constructor
constructor(elements: Elements, options: ElementsAssertionsOptions);
property not
readonly not: ElementsAssertions;
class ElementValue
class ElementValue<T> implements PromiseLike<T> {}
constructor
constructor(value: T | PromiseLike<T>, nightwatchInstance: NightwatchClient);
property assert
readonly assert: ValueAssertions<T>;
property value
value: Promise<T>;
method map
map: <K>(callback: (value: T) => K | PromiseLike<K>) => ElementValue<K>;
method then
then: <R1 = T, R2 = never>( onfulfilled?: (value: T) => R1 | PromiseLike<R1>, onrejected?: (reason: any) => R2 | PromiseLike<R2>) => PromiseLike<R1 | R2>;
class ValueAssertions
class ValueAssertions<T> {}
constructor
constructor(scopedValue: ElementValue<T>, options: ValueAssertionsOptions);
property not
readonly not: ValueAssertions<T>;
property scopedValue
scopedValue: ElementValue<T>;
method contains
contains: (expected: string, message?: string) => Promise<T>;
method equals
equals: (expected: T, message?: string) => Promise<T>;
method matches
matches: (expected: string | RegExp, message?: string) => Promise<T>;
Interfaces
interface AlertsNsCommands
interface AlertsNsCommands<ReturnType = unknown> {}
method accept
accept: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Accepts the currently displayed alert dialog. Usually, this is equivalent to clicking on the 'OK' button in the dialog.
Example 1
module.exports = { 'accept open alert': function (browser) { browser .alerts.accept(function () { console.log('alert accepted successfully'); }); },
'accept open alert with ES6 async/await': async function (browser) { await browser.alerts.accept(); } };
method dismiss
dismiss: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Dismisses the currently displayed alert dialog.
For confirm() and prompt() dialogs, this is equivalent to clicking the 'Cancel' button. For alert() dialogs, this is equivalent to clicking the 'OK' button.
Example 1
module.exports = { 'dismiss open alert': function (browser) { browser .alerts.dismiss(function () { console.log('alert dismissed successfully'); }); },
'dismiss open alert with ES6 async/await': async function (browser) { await browser.alerts.dismiss(); } };
method getText
getText: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<IfUnknown<ReturnType, this>, string>;
Get the text of the currently displayed JavaScript alert(), confirm(), or prompt() dialog.
Example 1
module.exports = { 'get open alert text': function (browser) { browser .alerts.getText(function (result) { console.log('text on open alert:', result.value); }); },
'get open alert text with ES6 async/await': async function (browser) { const alertText = await browser.alerts.getText(); console.log('text on open alert:', alertText); } };
method setText
setText: ( value: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Send keystrokes to a JavaScript prompt() dialog.
Example 1
module.exports = { 'set text on JS prompt': function (browser) { browser .alerts.setText('some text', function () { console.log('text sent to JS prompt successfully'); }); },
'set text on JS prompt with ES6 async/await': async function (browser) { await browser.alerts.setText('some text'); } };
interface AppiumCommands
interface AppiumCommands<ReturnType = unknown> {}
method getContext
getContext: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string | null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, string | null>;
Get the current context in which Appium is running. Used when testing hybrid mobile apps using Appium.
More info here: https://appium.io/docs/en/commands/context/get-context/
Example 1
module.exports = { 'get current context': function (app) { app .appium.getContext(function (result) { console.log('the current context is:', result.value); }); },
'get current context with ES6 async/await': async function (app) { const context = await app.appium.getContext(); console.log('the current context is:', context); } };
method getContexts
getContexts: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string[]> ) => void) => Awaitable<IfUnknown<ReturnType, this>, string[]>;
Get a list of the available contexts. Used when testing hybrid mobile apps using Appium.
More info here: https://appium.io/docs/en/commands/context/get-contexts/
Example 1
module.exports = { 'get available contexts': function (app) { app .appium.getContexts(function (result) { console.log('the available contexts are:', result.value); }); },
'get available contexts with ES6 async/await': async function (app) { const contexts = await app.appium.getContexts(); console.log('the available contexts are:', contexts); } };
method getCurrentActivity
getCurrentActivity: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<IfUnknown<ReturnType, this>, string>;
Get the name of the current Android activity.
Example 1
module.exports = { 'get current activity name': function (app) { app .appium.getCurrentActivity(function (result) { console.log('current android activity is:', result.value); }); },
'get current activity name with ES6 async/await': async function (app) { const activity = await app.appium.getCurrentActivity(); console.log('current android activity is:', activity); } };
method getCurrentPackage
getCurrentPackage: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<IfUnknown<ReturnType, this>, string>;
Get the name of the current Android package.
Example 1
module.exports = { 'get current package name': function (app) { app .appium.getCurrentPackage(function (result) { console.log('current android package is:', result.value); }); },
'get current package name with ES6 async/await': async function (app) { const packageName = await app.appium.getCurrentPackage(); console.log('current android package is:', packageName); } };
method getGeolocation
getGeolocation: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<AppiumGeolocation> ) => void) => Awaitable<IfUnknown<ReturnType, this>, AppiumGeolocation>;
Get the current geolocation of the mobile device.
Example 1
module.exports = { 'get device geolocation': function (app) { app .appium.getGeolocation(function (result) { console.log('current device geolocation is:', result.value); }); },
'get device geolocation with ES6 async/await': async function (app) { const location = await app.appium.getGeolocation(); console.log('current device geolocation is:', location); } };
method getOrientation
getOrientation: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<'LANDSCAPE' | 'PORTRAIT'> ) => void) => Awaitable<IfUnknown<ReturnType, this>, 'LANDSCAPE' | 'PORTRAIT'>;
Get the current device orientation.
Example 1
module.exports = { 'get current device orientation': function (app) { app .appium.getOrientation(function (result) { console.log('current device orientation is:', result.value); }); },
'get current device orientation with ES6 async/await': async function (app) { const orientation = await app.appium.getOrientation(); console.log('current device orientation is:', orientation); } };
method hideKeyboard
hideKeyboard: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void) => Awaitable<IfUnknown<ReturnType, this>, boolean>;
Hide soft keyboard.
Example 1
module.exports = { 'hide device soft keyboard': function (app) { app .appium.hideKeyboard(); },
'hide device soft keyboard with ES6 async/await': async function (app) { await app.appium.hideKeyboard(); } };
method isKeyboardShown
isKeyboardShown: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void) => Awaitable<IfUnknown<ReturnType, this>, boolean>;
Whether or not the soft keyboard is shown.
Example 1
module.exports = { 'whether keyboard is shown': function (app) { app .appium.isKeyboardShown(function (result) { console.log('result value of whether keyboard is shown:', result.value); }); },
'whether keyboard is shown with ES6 async/await': async function (app) { const result = await app.appium.isKeyboardShown(); console.log('result value of whether keyboard is shown:', result); } };
method longPressKeyCode
longPressKeyCode: { ( keycode: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<IfUnknown<ReturnType, this>, null>; ( keycode: number, metastate?: number, flags?: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<IfUnknown<ReturnType, this>, null>;};
Press and hold a particular key on an Android Device.
See [official Android Developers docs](https://developer.android.com/reference/android/view/KeyEvent.html) for reference of available Android key code values.
Example 1
module.exports = { 'long press e with caps lock on (keycode 33 and metastate 1048576)': function (app) { app .appium.longPressKeyCode(33, 1048576); },
'long press g (keycode 35) with ES6 async/await': async function (app) { await app.appium.longPressKeyCode(35); } };
method pressKeyCode
pressKeyCode: { ( keycode: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<IfUnknown<ReturnType, this>, null>; ( keycode: number, metastate?: number, flags?: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<IfUnknown<ReturnType, this>, null>;};
Press a particular key on an Android Device.
See [official Android Developers docs](https://developer.android.com/reference/android/view/KeyEvent.html) for reference of available Android key code values.
Example 1
module.exports = { 'press e with caps lock on (keycode 33 and metastate 1048576)': function (app) { app .appium.pressKeyCode(33, 1048576); },
'press g (keycode 35) with ES6 async/await': async function (app) { await app.appium.pressKeyCode(35); } };
method resetApp
resetApp: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Reset the current session (run delete and create session).
More info here: https://appium.io/docs/en/2.3/commands/base-driver/#reset
Example 1
module.exports = { 'start an android activity': function (app) { app .appium.resetApp(); },
'reset the app activity and wait for onboarding activity to start': function (app) { app .appium.resetApp(); } };
method setContext
setContext: ( context: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Set the context to be automated. Used when testing hybrid mobile apps using Appium.
More info here: https://appium.io/docs/en/commands/context/set-context/
Example 1
module.exports = { 'switch to webview context': async function (app) { app .waitUntil(async function() { // wait for webview context to be available // initially, this.getContexts() only returns ['NATIVE_APP'] const contexts = await this.appium.getContexts();
return contexts.length > 1; }) .perform(async function() { // switch to webview context const contexts = await this.appium.getContexts(); // contexts: ['NATIVE_APP', 'WEBVIEW_'] await this.appium.setContext(contexts[1]); }); },
'switch to native context': function (app) { app.appium.setContext('NATIVE_APP'); } };
method setGeolocation
setGeolocation: ( coordinates: AppiumGeolocation, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<AppiumGeolocation> ) => void) => Awaitable<IfUnknown<ReturnType, this>, AppiumGeolocation>;
Set the current geolocation of the mobile device.
Example 1
module.exports = { 'set geolocation to Tokyo, Japan': function (app) { app .appium.setGeolocation({latitude: 35.689487, longitude: 139.691706, altitude: 5}); },
'set geolocation to Tokyo, Japan with ES6 async/await': async function (app) { await app.appium.setGeolocation({latitude: 35.689487, longitude: 139.691706}); } };
method setOrientation
setOrientation: ( orientation: 'LANDSCAPE' | 'PORTRAIT', callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<'LANDSCAPE' | 'PORTRAIT'> ) => void) => Awaitable<IfUnknown<ReturnType, this>, 'LANDSCAPE' | 'PORTRAIT'>;
Set the current device orientation.
Example 1
module.exports = { 'set orientation to LANDSCAPE': function (app) { app .appium.setOrientation('LANDSCAPE'); } };
method startActivity
startActivity: ( opts: { appPackage: string; appActivity: string; appWaitPackage?: string; appWaitActivity?: string; intentAction?: string; intentCategory?: string; intentFlags?: string; optionalIntentArguments?: string; dontStopAppOnReset?: boolean; }, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Start an Android activity by providing package name, activity name and other optional parameters.
More info here: https://appium.io/docs/en/commands/device/activity/start-activity/
Example 1
module.exports = { 'start an android activity': function (app) { app .appium.startActivity({ appPackage: 'com.android.chrome', appActivity: 'com.google.android.apps.chrome.Main' }); },
'start the main Android activity and wait for onboarding activity to start': function (app) { app .appium.startActivity({ appPackage: 'org.wikipedia', appActivity: 'org.wikipedia.main.MainActivity', appWaitActivity: 'org.wikipedia.onboarding.InitialOnboardingActivity' }); } };
interface AppiumGeolocation
interface AppiumGeolocation {}
interface Assert
interface Assert<ReturnType = unknown> extends NightwatchAssertions<ReturnType>, NightwatchNodeAssertions<ReturnType> {}
interface ChromeNsCommands
interface ChromeNsCommands<ReturnType = unknown> {}
method deleteNetworkConditions
deleteNetworkConditions: () => Awaitable<IfUnknown<ReturnType, this>, null>;
Delete Chromium network emulation settings.
method getCastIssueMessage
getCastIssueMessage: () => Awaitable<IfUnknown<ReturnType, this>, string>;
Returns an error message when there is any issue in a Cast session.
method getCastSinks
getCastSinks: () => Awaitable<IfUnknown<ReturnType, this>, string[]>;
Returns the list of cast sinks (Cast devices) available to the Chrome media router.
An array of Strings containing the friendly device names of available cast sink targets.
method getNetworkConditions
getNetworkConditions: () => Awaitable< IfUnknown<ReturnType, this>, NetworkConditionsSpec>;
Get Chromium network emulation settings.
Network conditions must be set before it can be retrieved.
method launchApp
launchApp: (id: string) => Awaitable<IfUnknown<ReturnType, this>, null>;
Launch Chrome App with given ID.
Parameter id
ID of the App to launch.
method sendAndGetDevToolsCommand
sendAndGetDevToolsCommand: ( cmd: string, params?: { [key: string]: any }) => Awaitable<IfUnknown<ReturnType, this>, unknown>;
Sends an arbitrary devtools command to the browser and get the result.
Parameter cmd
The name of the command to send.
Parameter params
The command parameters.
See Also
<https://chromedevtools.github.io/devtools-protocol/>
method sendDevToolsCommand
sendDevToolsCommand: ( cmd: string, params?: { [key: string]: any }) => Awaitable<IfUnknown<ReturnType, this>, null>;
Sends an arbitrary devtools command to the browser.
Parameter cmd
The name of the command to send.
Parameter params
The command parameters.
See Also
<https://chromedevtools.github.io/devtools-protocol/>
method setCastSinkToUse
setCastSinkToUse: ( deviceName: string) => Awaitable<IfUnknown<ReturnType, this>, null>;
Selects a cast sink (Cast device) as the recipient of media router intents (connect or play).
Parameter deviceName
name of the target device.
method setDownloadPath
setDownloadPath: (path: string) => Awaitable<IfUnknown<ReturnType, this>, null>;
Sends a DevTools command to change the browser's download directory.
Parameter path
The desired download directory.
See Also
chrome.sendDevToolsCommand
method setNetworkConditions
setNetworkConditions: ( spec: NetworkConditionsSpec) => Awaitable<IfUnknown<ReturnType, this>, null>;
Set Chromium network emulation settings.
Parameter spec
Defines the network conditions to set
Example 1
describe('set network conditions', function() { it('sets the network conditions', function() { browser .chrome.setNetworkConditions({ offline: false, latency: 5, // Additional latency (ms). download_throughput: 500 * 1024, // Maximal aggregated download throughput. upload_throughput: 500 * 1024 // Maximal aggregated upload throughput. }); }); });
method setPermission
setPermission: ( name: string, state: 'granted' | 'denied' | 'prompt') => Awaitable<IfUnknown<ReturnType, this>, null>;
Set a permission state to the given value.
Parameter name
A name of the permission to update.
Parameter state
State to set permission to.
See Also
<https://w3c.github.io/permissions/#permission-registry> for valid names
method startCastTabMirroring
startCastTabMirroring: ( deviceName: string) => Awaitable<IfUnknown<ReturnType, this>, null>;
Initiates tab mirroring for the current browser tab on the specified device.
Parameter deviceName
name of the target device.
method stopCasting
stopCasting: ( deviceName: string) => Awaitable<IfUnknown<ReturnType, this>, null>;
Stops casting from media router to the specified device, if connected.
Parameter deviceName
name of the target device.
interface ChromiumClientCommands
interface ChromiumClientCommands {}
property captureBrowserConsoleLogs
captureBrowserConsoleLogs: LogsNsCommands<this>['captureBrowserConsoleLogs'];
property captureBrowserExceptions
captureBrowserExceptions: LogsNsCommands<this>['captureBrowserExceptions'];
property captureNetworkRequests
captureNetworkRequests: NetworkNsCommands<this>['captureRequests'];
property mockNetworkResponse
mockNetworkResponse: NetworkNsCommands<this>['mockResponse'];
property setNetworkConditions
setNetworkConditions: NetworkNsCommands<this>['setConditions'];
method enablePerformanceMetrics
enablePerformanceMetrics: ( enable?: boolean, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Enable/disable the collection of performance metrics in the browser. Metrics collection only begin after this command is called.
Example 1
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 Also
https://web.dev/metrics/
https://pptr.dev/api/puppeteer.page.metrics/
method getPerformanceMetrics
getPerformanceMetrics: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<{ [metricName: string]: number }> ) => void) => Awaitable<this, { [metricName: string]: number }>;
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 1
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 Also
https://web.dev/metrics/
https://pptr.dev/api/puppeteer.page.metrics/
method setDeviceDimensions
setDeviceDimensions: ( metrics?: { width?: number; height?: number; deviceScaleFactor?: number; mobile?: boolean; }, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Override device mode/dimensions.
Example 1
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 Also
https://nightwatchjs.org/guide/mobile-web-testing/override-device-dimensions.html
method setGeolocation
setGeolocation: ( coordinates?: { latitude: number; longitude: number; accuracy?: number }, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Mock the geolocation of the browser.
Call without any arguments to reset the geolocation.
Example 1
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 Also
https://nightwatchjs.org/guide/network-requests/mock-geolocation.html
method takeHeapSnapshot
takeHeapSnapshot: ( heapSnapshotLocation?: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<this, string>;
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 theresult
argument passed to the callback, in string-serialized JSON format.Returns
A promise that contains heap snapshot in string-serialized JSON format.
Example 1
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 Also
https://nightwatchjs.org/guide/running-tests/take-heap-snapshot.html
interface ClientCommands
interface ClientCommands extends ChromiumClientCommands {}
method axeInject
axeInject: () => Awaitable<this, null>;
Injects the [axe-core](https://github.com/dequelabs/axe-core) js library into the current page (using the
.executeScript()
command). To be paired with.axeRun()
to evaluate the axe-core accessibility rules.Example 1
describe('accessibility testing', function () { it('accessibility rule subset', function (browser) { browser .url('https://www.w3.org/WAI/demos/bad/after/home.html') .assert.titleEquals('Welcome to CityLights! [Accessible Home Page]') .axeInject() .axeRun('body', { runOnly: ['color-contrast', 'image-alt'], }); }); });
See Also
https://nightwatchjs.org/api/axeInject.html
method axeRun
axeRun: ( context?: unknown, options?: { [key: string]: any }, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<{ [key: string]: any }> ) => void) => Awaitable<this, { [key: string]: any }>;
Analyzes the current page against applied axe rules.
Parameter context
Defines the scope of the analysis, will cascade to child elements. See [axe-core docs](https://github.com/dequelabs/axe-core/blob/master/doc/API.md#context-parameter) for more details.
Parameter options
Allows configuration of what rules will be run (accessibility standard or rules to enable/disable). See [axe-core docs](https://www.deque.com/axe/core-documentation/api-documentation/#options-parameter) for more details.
Parameter callback
Optional callback function which is called with the results.
Example 1
describe('accessibility testing', function () { it('accessibility rule subset', function (browser) { browser .url('https://www.w3.org/WAI/demos/bad/after/home.html') .assert.titleEquals('Welcome to CityLights! [Accessible Home Page]') .axeInject() .axeRun('body', { runOnly: ['color-contrast', 'image-alt'], }); });
it('accessibility rule subset 2', function (browser) { browser .url('https://nightwatchjs.org') .axeInject() .axeRun(['#navBar', 'nav'], { rules: { 'color-contrast': { enabled: false }, } }); }); });
See Also
method closeWindow
closeWindow: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
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 1
describe('closeWindow command demo' , function (result) { test('demo test', function () { browser.closeWindow(); }); });
See Also
https://nightwatchjs.org/api/closeWindow.html
Deprecated
In favour of
.window.close()
.
method debug
debug: ( config?: { useGlobal?: boolean; preview?: boolean; timeout?: number }, callback?: (this: NightwatchAPI) => void) => Awaitable<this, undefined>;
This command halts the test execution and provides users with a REPL interface where they can type any of the available Nightwatch commands and the command will be executed in the running browser in real-time.
This can be used to debug why a certain command in not working as expected, find the correct locators for your assertions or just play around with the available Nightwatch commands.
Example 1
// async function is required while using the debug // command to get the correct result as output. this.demoTest = async function (browser) { browser.debug();
// with no auto-complete browser.debug({preview: false});
// with a timeout of 6000 ms (time for which the interface // would wait for a result). browser.debug({timeout: 6000}) };
See Also
https://nightwatchjs.org/api/debug.html
method deleteCookie
deleteCookie: ( cookieName: string, 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 1
this.demoTest = function() { browser.deleteCookie("test_cookie", function() { // do something more in here }); }
See Also
https://nightwatchjs.org/api/deleteCookie.html
Deprecated
In favour of
.cookies.delete()
.
method deleteCookies
deleteCookies: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Delete all cookies visible to the current page.
Example 1
this.demoTest = function() { browser.deleteCookies(function() { // do something more in here }); }
See Also
https://nightwatchjs.org/api/deleteCookies.html
Deprecated
In favour of
.cookies.deleteAll()
.
method end
end: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Ends the session. Uses session protocol command.
Example 1
this.demoTest = function () { browser.end(); };
See Also
https://nightwatchjs.org/api/end.html
method fullscreenWindow
fullscreenWindow: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Sets the current window state to fullscreen.
Example 1
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 Also
https://nightwatchjs.org/api/fullscreenWindow.html
Deprecated
In favour of
.window.fullscreen()
.
method getCookie
getCookie: ( name: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<Cookie> ) => void) => Awaitable<this, Cookie>;
Retrieve a single cookie visible to the current page. The cookie is returned as a cookie JSON object, as defined [here](https://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object).
Uses
cookie
protocol command.Example 1
this.demoTest = function() { browser.getCookie(name, function callback(result) { this.assert.equal(result.value, '123456'); this.assert.equals(result.name, 'test_cookie'); }); }
See Also
https://nightwatchjs.org/api/getCookie.html
Deprecated
In favour of
.cookies.get()
.
method getCookies
getCookies: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<Cookie[]> ) => void) => Awaitable<this, Cookie[]>;
Retrieve all cookies visible to the current page. The cookies are returned as an array of cookie JSON object, as defined [here](https://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object).
Uses
cookie
protocol command.Example 1
this.demoTest = function() { browser.getCookies(function callback(result) { this.assert.equal(result.value.length, 1); this.assert.equals(result.value[0].name, 'test_cookie'); }); }
See Also
https://nightwatchjs.org/api/getCookies.html
Deprecated
In favour of
.cookies.getAll()
.
method getCurrentUrl
getCurrentUrl: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<this, string>;
Retrieve the URL of the current page.
Example 1
describe('Navigation commands demo', function() { test('demoTest', function(browser) { // navigate to new url: browser.navigateTo('https://nightwatchjs.org');
// Retrieve to url with callback: browser.getCurrentUrl(function(result) { console.log(result.value); }); });
test('demoTestAsync', async function(browser) { const currentUrl = await browser.navigateTo('https://nightwatchjs.org').getCurrentUrl(); console.log('currentUrl:', currentUrl); // will print 'https://nightwatchjs.org' });
});
See Also
https://nightwatchjs.org/api/getCurrentUrl.html
method getLog
getLog: ( typestring: string, callback?: (this: NightwatchAPI, log: NightwatchLogEntry[]) => void) => Awaitable<this, NightwatchLogEntry[]>;
Gets a log from Selenium.
Example 1
this.demoTest = function() { this.getLog('browser', function(logEntriesArray) { console.log('Log length: ' + logEntriesArray.length); logEntriesArray.forEach(function(log) { console.log('[' + log.level + '] ' + log.timestamp + ' : ' + log.message); }); }); };
See Also
https://nightwatchjs.org/api/getLog.html
method getLogTypes
getLogTypes: ( callback?: (this: NightwatchAPI, result: NightwatchLogTypes[]) => void) => Awaitable<this, NightwatchLogTypes[]>;
Gets the available log types. More info about log types in WebDriver can be found here: https://github.com/SeleniumHQ/selenium/wiki/Logging
Example 1
this.demoTest = function() { this.getLogTypes(function(typesArray) { console.log(typesArray); }); };
See Also
https://nightwatchjs.org/api/getLogTypes.html
method getTitle
getTitle: ( callback?: (this: NightwatchAPI, result: string) => void) => Awaitable<this, string>;
Returns the title of the current page. Uses title protocol command.
Example 1
this.demoTest = function () { browser.getTitle(function(title) { this.assert.equal(typeof title, 'string'); this.assert.equal(title, 'Nightwatch.js'); }); };
See Also
https://nightwatchjs.org/api/getTitle.html
method getWindowPosition
getWindowPosition: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<WindowPosition> ) => void) => Awaitable<this, WindowPosition>;
Retrieves the current window position.
For clients which are compatible with the [W3C Webdriver API](https://w3c.github.io/webdriver/),
getWindowPosition
is an alias ofgetWindowRect
.The
getWindowRect
command returns both dimensions and position of the window, using thewindowRect
protocol command.Example 1
module.exports = { 'demo test .getWindowPosition()': function(browser) { // Retrieve the attributes browser.getWindowPosition(function(value) { console.log(value); }); },
'getWindowPosition ES6 demo test': async function(browser) { const value = await browser.getWindowPosition(); console.log('value', value); } }
See Also
https://nightwatchjs.org/api/getWindowPosition.html
Deprecated
In favour of
.window.getPosition()
.
method getWindowRect
getWindowRect: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<WindowSizeAndPosition> ) => void) => Awaitable<this, WindowSizeAndPosition>;
Change or get the [window rect](https://w3c.github.io/webdriver/#dfn-window-rect). This is defined as a dictionary of the
screenX
,screenY
,outerWidth
andouterHeight
attributes of the window.Its JSON representation is the following: -
x
- window's screenX attribute; -y
- window's screenY attribute; -width
- outerWidth attribute; -height
- outerHeight attribute.All attributes are in in CSS pixels. To change the window react, you can either specify
width
andheight
,x
andy
or all properties together.Example 1
module.exports = { 'demo test .getWindowRect()': function() { // Retrieve the attributes browser.getWindowRect(function(value) { console.log(value); }); },
'getWindowRect ES6 demo test': async function() { const resultValue = await browser.getWindowRect(); console.log('result value', resultValue); } }
See Also
https://nightwatchjs.org/api/getWindowRect.html
Deprecated
In favour of
.window.getRect()
.
method getWindowSize
getWindowSize: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<WindowSizeAndPosition> ) => void) => Awaitable<this, WindowSizeAndPosition>;
Retrieves the current window size.
For clients which are compatible with the [W3C Webdriver API](https://w3c.github.io/webdriver/),
getWindowSize
is an alias ofgetWindowRect
.The
getWindowRect
command returns both dimensions and position of the window, using thewindowRect
protocol command.Example 1
module.exports = { 'demo test .getWindowSize()': function() { // Retrieve the attributes browser.getWindowSize(function(value) { console.log(value); }); },
'getWindowSize ES6 demo test': async function(browser) { const value = await browser.getWindowSize(); console.log('value', value); } }
See Also
https://nightwatchjs.org/api/getWindowSize.html
Deprecated
In favour of
.window.getRect()
.
method init
init: ( url?: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
This command is an alias to url and also a convenience method when called without any arguments in the sense that it performs a call to .url() with passing the value of
launch_url
field from the settings file. Usesurl
protocol command.Example 1
this.demoTest = function () { browser.init(); };
See Also
https://nightwatchjs.org/api/init.html
method injectScript
injectScript: { ( scriptUrl: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<WebElement> ) => void ): Awaitable<this, WebElement>; ( scriptUrl: string, id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<WebElement> ) => void ): Awaitable<this, WebElement>;};
Utility command to load an external script into the page specified by url.
Example 1
this.demoTest = function() { this.injectScript("{script-url}", function() { // we're all done here. }); };
See Also
https://nightwatchjs.org/api/injectScript.html
Deprecated
In favour of
.document.injectScript()
.
method isLogAvailable
isLogAvailable: ( typeString: string, callback?: (this: NightwatchAPI, result: boolean) => void) => Awaitable<this, boolean>;
Utility command to test if the log type is available.
Example 1
this.demoTest = function() { browser.isLogAvailable('browser', function(isAvailable) { // do something more in here }); }
See Also
https://nightwatchjs.org/api/isLogAvailable.html
method maximizeWindow
maximizeWindow: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Maximizes the current window.
Example 1
this.demoTest = function () { browser.maximizeWindow(); };
See Also
https://nightwatchjs.org/api/maximizeWindow.html
Deprecated
In favour of
.window.maximize()
.
method minimizeWindow
minimizeWindow: ( 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 1
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 Also
https://nightwatchjs.org/api/minimizeWindow.html
Deprecated
In favour of
.window.minimize()
.
method navigateTo
navigateTo: ( url: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Navigate to a new URL. This method will also call the
onBrowserNavigate()
test global, right after the page is loaded.Example 1
describe('Navigation commands demo', function() { test('demoTest', function(browser) { // navigate to new url: browser.navigateTo('https://nightwatchjs.org');
// Retrieve to url with callback: browser.getCurrentUrl(function(result) { console.log(result.value); }); });
test('demoTestAsync', async function(browser) { const currentUrl = await browser.navigateTo('https://nightwatchjs.org').getCurrentUrl(); console.log('currentUrl:', currentUrl); // will print 'https://nightwatchjs.org' }); });
See Also
https://nightwatchjs.org/api/navigateTo.html
method openNewWindow
openNewWindow: ( type?: WindowType, 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 1
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 Also
https://nightwatchjs.org/api/openNewWindow.html
Deprecated
In favour of
.window.open()
.
method pageSource
pageSource: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<this, string>;
Returns the page source. Uses pageSource protocol command.
Example 1
this.demoTest = function (browser) { browser.pageSource(function(pageSource) { console.log(pageSource); }); };
See Also
https://nightwatchjs.org/api/pageSource.html
Deprecated
In favour of
.document.pageSource()
.
method pause
pause: ( ms?: number, callback?: (this: NightwatchAPI) => void) => Awaitable<this, undefined>;
Suspends the test for the given time in milliseconds. If the milliseconds argument is missing it will suspend the test indefinitely
Example 1
this.demoTest = function () { browser.pause(1000); // or suspend indefinitely browser.pause(); };
See Also
https://nightwatchjs.org/api/pause.html
method perform
perform: { <ReturnValue>( callback: (this: NightwatchAPI) => ReturnValue | Promise<ReturnValue> ): Awaitable<this, ReturnValue>; <ReturnValue>( callback: ( this: NightwatchAPI, client: NightwatchAPI, done: (result?: ReturnValue) => void ) => void ): Awaitable<this, ReturnValue>; <ReturnValue>( callback: ( this: NightwatchAPI, done: (result?: ReturnValue) => void ) => void ): Awaitable<this, ReturnValue>;};
A simple perform command which allows access to the Nightwatch API in a callback. Can be useful if you want to read variables set by other commands.
The callback signature can have up to two parameters. - no parameters: callback runs and perform completes immediately at the end of the execution of the callback. - one parameter: allows for asynchronous execution within the callback providing a done callback function for completion as the first argument. - two parameters: allows for asynchronous execution with the Nightwatch
api
object passed in as the first argument, followed by the done callback.Example 1
describe('perform example', function() { var elementValue;
it('basic perform', function(browser) { browser .getValue('.some-element', function(result) { elementValue = result.value; }) // other stuff going on ...
// self-completing callback .perform(function() { console.log('elementValue', elementValue); // without any defined parameters, perform // completes immediately (synchronously) })
// returning a Promise .perform(async function() { //
this
can be used to directly access Nightwatch API const sessionId = await this.sessionId; console.log('session id', sessionId); })// DEPRECATED: asynchronous completion using done .perform(function(done: (result: string) => void) { // potentially some async stuff going on //
this
can be used to directly access Nightwatch API this.getTitle((result) => { // when finished, call the done callback done(result.value); }); })// DEPRECATED: asynchronous completion including api (client) .perform(function(client: NightwatchAPI, done: () => void) { this.navigateTo('https://google.com/', () => { done(); }); }); });
it('perform with async', function(browser) { const result = await browser.perform(async function() { //
this
can be used to directly access Nightwatch API const pageTitle = await this.getTitle();return 100; }); console.log('result:', result); // 100 }) };
method quit
quit: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Ends the session and closes down the test WebDriver server, if one is running. This is similar to calling the .end() command, but the former doesn't quit the WebDriver session.
This command will also execute the
onBrowserQuit()
global, if one is defined.Example 1
this.demoTest = function (browser) { browser.quit(function(result) { console.log(result.value); }); }
See Also
https://nightwatchjs.org/api/quit.html
method resizeWindow
resizeWindow: ( width: number, height: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Resizes the current window.
Example 1
this.demoTest = function () { browser.resizeWindow(1000, 800); };
See Also
https://nightwatchjs.org/api/resizeWindow.html
Deprecated
In favour of
.window.resize()
.
method saveScreenshot
saveScreenshot: ( fileName: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<this, string>;
Take a screenshot of the current page and saves it as the given filename.
Example 1
this.demoTest = function ( ) { browser.saveScreenshot('/path/to/fileName.png'); };
See Also
https://nightwatchjs.org/api/saveScreenshot.html
method setCookie
setCookie: ( cookie: Cookie, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Set a cookie, specified as a cookie JSON object, as defined [here](https://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object).
Uses
cookie
protocol command.Example 1
this.demoTest = function() { browser.setCookie({ name : "test_cookie", value : "test_value", path : "/", (Optional) domain : "example.org", (Optional) secure : false, (Optional) httpOnly : false, // (Optional) expiry : 1395002765 // (Optional) time in seconds since midnight, January 1, 1970 UTC }); }
See Also
https://nightwatchjs.org/api/setCookie.html
Deprecated
In favour of
.cookies.set()
.
method setWindowPosition
setWindowPosition: ( offsetX: number, offsetY: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Sets the current window position.
Example 1
this.demoTest = function () { browser.setWindowPosition(0, 0); };
See Also
https://nightwatchjs.org/api/setWindowPosition.html
Deprecated
In favour of
.window.setPosition()
.
method setWindowRect
setWindowRect: ( options: WindowSizeAndPosition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Change the [window rect](https://w3c.github.io/webdriver/#dfn-window-rect). This is defined as a dictionary of the
screenX
,screenY
,outerWidth
andouterHeight
attributes of the window.Its JSON representation is the following: -
x
- window's screenX attribute; -y
- window's screenY attribute; -width
- outerWidth attribute; -height
- outerHeight attribute.All attributes are in in CSS pixels. To change the window react, you can either specify
width
andheight
,x
andy
or all properties together.Example 1
module.exports = { 'demo test .setWindowRect()': function() {
// Change the screenX and screenY attributes of the window rect. browser.setWindowRect({x: 500, y: 500});
// Change the width and height attributes of the window rect. browser.setWindowRect({width: 600, height: 300});
// Retrieve the attributes browser.setWindowRect(function(result) { console.log(result.value); }); },
'setWindowRect ES6 demo test': async function() { await browser.setWindowRect({ width: 600, height: 300, x: 100, y: 100 }); } }
See Also
https://nightwatchjs.org/api/setWindowRect.html
Deprecated
In favour of
.window.setRect()
.
method setWindowSize
setWindowSize: ( width: number, height: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Sets the current window position.
Example 1
this.demoTest = function () { browser.setWindowPosition(0, 0); };
See Also
https://nightwatchjs.org/api/setWindowSize.html
Deprecated
In favour of
.window.setSize()
.
method switchToWindow
switchToWindow: ( handleOrName: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Change focus to another window. The window to change focus to may be specified by its server assigned window handle, or by the value of its name attribute.
To find out the window handle use
windowHandles
commandExample 1
this.demoTest = function () { browser.windowHandles(function(result) { const handle = result.value[0]; browser.switchToWindow(handle); }); };
this.demoTestAsync = async function () { const result = await browser.windowHandles(); const handle = result[0]; browser.switchToWindow(handle); };
See Also
https://nightwatchjs.org/api/switchToWindow.html
Deprecated
In favour of
.window.switchTo()
.
method switchWindow
switchWindow: ( handleOrName: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Change focus to another window. The window to change focus to may be specified by its server assigned window handle, or by the value of its name attribute.
To find out the window handle use
windowHandles
commandExample 1
this.demoTest = function () { browser.windowHandles(function(result) { const handle = result.value[0]; browser.switchWindow(handle); }); };
this.demoTestAsync = async function () { const result = await browser.windowHandles(); const handle = result[0]; browser.switchWindow(handle); };
switchToWindow
See Also
https://nightwatchjs.org/api/switchWindow.html
Deprecated
In favour of
.window.switch()
.
method urlHash
urlHash: ( hash: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Convenience command that adds the specified hash (i.e. url fragment) to the current value of the
launch_url
as set innightwatch.json
.Example 1
this.demoTest = function () { browser.urlHash('#hashvalue'); // or browser.urlHash('hashvalue'); };
See Also
https://nightwatchjs.org/api/urlHash.html
method useCss
useCss: (callback?: (this: NightwatchAPI) => void) => Awaitable<this, undefined>;
Sets the locate strategy for selectors to
css selector
, therefore every following selector needs to be specified as css.Example 1
this.demoTest = function () { browser .useCss() // we're back to CSS now .setValue('input[type=text]', 'nightwatch'); };
See Also
https://nightwatchjs.org/api/useCss.html
method useXpath
useXpath: ( callback?: (this: NightwatchAPI) => void) => Awaitable<this, undefined>;
Sets the locate strategy for selectors to xpath, therefore every following selector needs to be specified as xpath.
Example 1
this.demoTest = function () { browser .useXpath() // every selector now must be xpath .click("//tr[@data-recordid]/span[text()='Search Text']"); };
See Also
https://nightwatchjs.org/api/useXpath.html
method waitUntil
waitUntil: { ( conditionFn: (this: NightwatchAPI) => void, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( conditionFn: (this: NightwatchAPI) => void, waitTimeMs: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( conditionFn: (this: NightwatchAPI) => void, waitTimeMs: number, retryInterval: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( conditionFn: (this: NightwatchAPI) => void, waitTimeMs: number, retryInterval: number, message: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Waits for a condition to evaluate to a "truthy" value. The condition may be specified by any function which returns the value to be evaluated or a Promise to wait for.
An optional wait time can be specified, otherwise the global waitForConditionTimeout value will be used.
Example 1
describe('waitUntil Example', function() { it('demo Test', function(browser) { browser .url('https://nightwatchjs.org') .waitUntil(async function() { const title = await this.execute(function() { return document.title; });
return title === 'Nightwatch.js'; }, 1000); }); });
interface CommandInstance
interface CommandInstance {}
method complete
complete: (...args: unknown[]) => void;
method httpRequest
httpRequest: (options: HttpRequestOptions) => Promise<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 Also
https://nightwatchjs.org/guide/extending-nightwatch/adding-custom-commands.html#postdoc-directly-calling-seleniumwebdriver-endpoints
method toString
toString: () => string;
index signature
get api(): NightwatchAPI;
index signature
get client(): NightwatchClient;
index signature
get commandArgs(): unknown[];
index signature
get commandFileName(): string;
index signature
get driver(): WebDriver;
index signature
get isES6AsyncCommand(): boolean;
index signature
get reuseBrowser(): boolean;
index signature
get transportActions(): unknown;
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:
interface TransportActions {getCurrentUrl(): Promise<NightwatchCallbackResult<string>>;}then use it inside your custom command like:
const currentUrl = await (this.transportActions as TransportActions).getCurrentUrl();
interface Cookie
interface Cookie {}
interface CookiesNsCommands
interface CookiesNsCommands<ReturnType = unknown> {}
method delete
delete: ( cookieName: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, 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 1
module.exports = { 'delete a cookie': function (browser) { browser .cookies.delete('test_cookie', function () { console.log('cookie deleted successfully'); }); },
'delete a cookie with ES6 async/await': async function (browser) { await browser.cookies.delete('test_cookie'); } };
method deleteAll
deleteAll: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Delete all cookies visible to the current page.
Example 1
module.exports = { 'delete all cookies': function (browser) { browser .cookies.deleteAll(function() { console.log('all cookies deleted successfully'); }); },
'delete all cookies with ES6 async/await': async function (browser) { await browser.cookies.deleteAll(); } };
method get
get: ( name: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<Cookie | null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, Cookie | null>;
Retrieve a single cookie visible to the current page.
The cookie is returned as a cookie JSON object, with properties as defined [here](https://www.w3.org/TR/webdriver/#dfn-table-for-cookie-conversion).
Example 1
module.exports = { 'get a cookie': function (browser) { browser .cookies.get('test_cookie', function (result) { const cookie = result.value; this.assert.equal(cookie.name, 'test_cookie'); this.assert.equal(cookie.value, '123456'); }); },
'get a cookie with ES6 async/await': async function (browser) { const cookie = await browser.cookies.get('test_cookie'); browser.assert.equal(cookie.name, 'test_cookie'); browser.assert.equal(cookie.value, '123456'); } };
method getAll
getAll: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<Cookie[]> ) => void) => Awaitable<IfUnknown<ReturnType, this>, Cookie[]>;
Retrieve all cookies visible to the current page.
The cookies are returned as an array of cookie JSON object, with properties as defined [here](https://www.w3.org/TR/webdriver/#dfn-table-for-cookie-conversion).
Example 1
module.exports = { 'get all cookies': function (browser) { browser .cookies.getAll(function (result) { this.assert.equal(result.value.length, 1); this.assert.equal(result.value[0].name, 'test_cookie'); }); },
'get all cookies with ES6 async/await': async function (browser) { const cookies = await browser.cookies.getAll(); browser.assert.equal(cookies.length, 1); browser.assert.equal(cookies[0].name, 'test_cookie'); } };
method set
set: ( cookie: Cookie, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Set a cookie, specified as a cookie JSON object, with properties as defined [here](https://www.w3.org/TR/webdriver/#dfn-table-for-cookie-conversion).
Example 1
module.exports = { 'set a cookie': function (browser) { browser .cookies.set({ name: "test_cookie", value: "test_value", path: "/", // (Optional) domain: "example.org", // (Optional) secure: false, // (Optional) httpOnly: false, // (Optional) expiry: 1395002765 // (Optional) time in seconds since midnight, January 1, 1970 UTC }); },
'set a cookie with ES6 async/await': async function (browser) { await browser.cookies.set({ name: 'test_cookie', value: 'test_value', domain: 'example.org', // (Optional) sameSite: 'Lax' // (Optional) }); } };
interface CreateClientParams
interface CreateClientParams {}
property browserName
browserName?: string | null;
property config
config?: string;
property debug
debug?: boolean;
property devtools
devtools?: boolean;
property enable_global_apis
enable_global_apis?: boolean;
property env
env?: string | null;
property globals
globals?: Partial<NightwatchGlobals>;
property headless
headless?: boolean;
property output
output?: boolean;
property parallel
parallel?: boolean;
property reporter
reporter?: any;
property silent
silent?: boolean;
property test_settings
test_settings?: Partial<NightwatchOptions>;
property timeout
timeout?: number | null;
property useAsync
useAsync?: boolean;
interface CustomCommandInstance
interface CustomCommandInstance extends CommandInstance {}
interface DocumentNsCommands
interface DocumentNsCommands<ReturnType = unknown> {}
method injectScript
injectScript: { ( scriptUrl: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<WebElement> ) => void ): Awaitable<IfUnknown<ReturnType, this>, WebElement>; ( scriptUrl: string, id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<WebElement> ) => void ): Awaitable<IfUnknown<ReturnType, this>, WebElement>;};
Utility command to load an external script into the page specified by url.
Example 1
module.exports = { 'inject external script': function (browser) { browser.document.injectScript('', function () { console.log('script injected successfully'); }); },
'inject external script using ES6 async/await': async function (browser) { await browser.document.injectScript('', 'injected-script'); } };
method pageSource
pageSource: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<IfUnknown<ReturnType, this>, string>;
Get the string serialized source of the current page.
Example 1
module.exports = { 'get page source': function (browser) { browser.document.pageSource(function (result) { console.log('current page source:', result.value); }); },
'get page source using ES6 async/await': async function (browser) { const pageSource = await browser.document.pageSource(); console.log('current page source:', pageSource); } };
document.source
method source
source: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<IfUnknown<ReturnType, this>, string>;
Get the string serialized source of the current page.
Example 1
module.exports = { 'get page source': function (browser) { browser.document.source(function (result) { console.log('current page source:', result.value); }); },
'get page source using ES6 async/await': async function (browser) { const pageSource = await browser.document.source(); console.log('current page source:', pageSource); } };
document.pageSource
interface ElementCommands
interface ElementCommands {}
method check
check: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Will check, click, on an unchecked checkbox or radio input if not already checked.
Example 1
module.exports = { demoTest(browser) { browser.check('input[type=checkbox]:not(:checked)');
browser.check('input[type=checkbox]:not(:checked)', function(result) { console.log('Check result', result); });
// with explicit locate strategy browser.check('css selector', 'input[type=checkbox]:not(:checked)');
// with selector object - see https://nightwatchjs.org/guide#element-properties browser.check({ selector: 'input[type=checkbox]:not(:checked)', index: 1, suppressNotFoundErrors: true });
browser.check({ selector: 'input[type=checkbox]:not(:checked)', timeout: 2000 // overwrite the default timeout (in ms) to check if the element is present }); },
demoTestAsync: async function(browser) { const result = await browser.check('input[type=checkbox]:not(:checked)'); console.log('Check result', result); } }
See Also
https://nightwatchjs.org/api/check.html
method clearValue
clearValue: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Clear a textarea or a text input element's value. Starting with v1.1
clearValue()
will wait for the element to be present (until the specified timeout).If the element is not found, an error is thrown which will cause the test to fail. Starting with
v1.2
you can suppress element not found errors by specifying thesuppressNotFoundErrors
flag.Example 1
describe('clearValue Command demo', function() { test('demo test', function() { browser.clearValue('#login input[type=text]');
browser.clearValue('#login input[type=text]', function(result) { console.log('clearValue result', result); });
// with explicit locate strategy browser.clearValue('css selector', '#login input[type=text]');
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.clearValue({ selector: '#login input[type=text]', index: 1, suppressNotFoundErrors: true });
browser.clearValue({ selector: '#login input[type=text]', timeout: 2000 // overwrite the default timeout (in ms) to check if the element is present });
});
});
See Also
https://nightwatchjs.org/api/clearValue.html
method click
click: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Simulates a click event on the given DOM element. The element is scrolled into view if it is not already pointer-interactable. See the WebDriver specification for element interactability.
Example 1
module.exports = { demoTest() { browser.click('#main ul li a.first');
browser.click('#main ul li a.first', function(result) { console.log('Click result', result); });
// with explicit locate strategy browser.click('css selector', '#main ul li a.first');
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.click({ selector: '#main ul li a', index: 1, suppressNotFoundErrors: true });
browser.click({ selector: '#main ul li a.first', timeout: 2000 // overwrite the default timeout (in ms) to check if the element is present }); },
demoTestAsync: async function(browser) { const result = await browser.click('#main ul li a.first'); console.log('Click result', result); } }
See Also
https://nightwatchjs.org/api/click.html
method clickAndHold
clickAndHold: { ( selector: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( using: LocateStrategy, selector: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Move to the element and click (without releasing) in the middle of the given element.
Example 1
module.exports = { demoTest() { browser.clickAndHold('#main ul li a.first');
browser.clickAndHold('#main ul li a.first', function(result) { console.log('Click result', result); });
// with explicit locate strategy browser.clickAndHold('css selector', '#main ul li a.first');
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.clickAndHold({ selector: '#main ul li a', index: 1, suppressNotFoundErrors: true });
browser.clickAndHold({ selector: '#main ul li a.first', timeout: 2000 // overwrite the default timeout (in ms) to check if the element is present }); },
demoTestAsync: async function() { const result = await browser.clickAndHold('#main ul li a.first'); console.log('Right click result', result); } }
See Also
https://nightwatchjs.org/api/clickAndHold.html#apimethod-container
method doubleClick
doubleClick: { ( selector: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( using: LocateStrategy, selector: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Move to the element and peforms a double-click in the middle of the element.
Example 1
module.exports = { demoTest() { browser.doubleClick('#main ul li a.first');
browser.doubleClick('#main ul li a.first', function(result) { console.log('double click result', result); });
// with explicit locate strategy browser.doubleClick('css selector', '#main ul li a.first');
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.doubleClick({ selector: '#main ul li a', index: 1, suppressNotFoundErrors: true });
browser.doubleClick({ selector: '#main ul li a.first', timeout: 2000 // overwrite the default timeout (in ms) to check if the element is present }); },
demoTestAsync: async function() { const result = await browser.doubleClick('#main ul li a.first'); console.log('double click result', result); } }
See Also
https://nightwatchjs.org/api/doubleClick.html#apimethod-container
method dragAndDrop
dragAndDrop: { ( selector: Definition, destination: NightwatchElement | NightwatchPosition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( using: LocateStrategy, selector: any, destination: NightwatchPosition | NightwatchElement, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Drag an element to the given position or destination element.
Example 1
module.exports = { demoTest(browser) { browser.dragAndDrop('#main', {x: 100, y:100}):
//using webElement as a destination demoTestAsync: async function(browser) { const destination = await browser.findElement('#upload'); browser.dragAndDrop('#main', destination.getId()); } }
See Also
https://nightwatchjs.org/api/dragAndDrop.html
method findElement
findElement: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<JSON_WEB_OBJECT> ) => void ): Awaitable<this, JSON_WEB_OBJECT>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<JSON_WEB_OBJECT> ) => void ): Awaitable<this, JSON_WEB_OBJECT>;};
Search for an elements on the page, starting from the document root. The located element will be returned as web element JSON object (with an added .getId() convenience method). First argument is the element selector, either specified as a string or as an object (with 'selector' and 'locateStrategy' properties).
Example 1
module.exports = { 'demo Test': function(browser) { const resultElement = await browser.findElement('.features-container li:first-child');
console.log('Element Id:', resultElement.getId()); } }
See Also
https://nightwatchjs.org/api/findElement.html
method findElements
findElements: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<JSON_WEB_OBJECT[]> ) => void ): Awaitable<this, JSON_WEB_OBJECT[]>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<JSON_WEB_OBJECT[]> ) => void ): Awaitable<this, JSON_WEB_OBJECT[]>;};
Search for multiple elements on the page, starting from the document root. The located elements will be returned as web element JSON objects (with an added .getId() convenience method). First argument is the element selector, either specified as a string or as an object (with 'selector' and 'locateStrategy' properties).
Example 1
module.exports = { 'demo Test': function(browser) { const resultElements = await browser.findElements('.features-container li');
resultElements.forEach(item => console.log('Element Id:', item.getId())); },
See Also
https://nightwatchjs.org/api/findElements.html
method getAccessibleName
getAccessibleName: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>;};
Returns the computed WAI-ARIA label of an element.
Example 1
module.exports = { demoTest() { browser.getAccessibleName('*[name="search"]', function(result) { this.assert.equal(typeof result, 'object); this.assert.equal(result.value, 'search input'); });
// with explicit locate strategy browser.getAccessibleName('css selector', '*[name="search"]', function(result) { console.log('getAccessibleName result', result.value); });
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.getAccessibleName({ selector: '*[name="search"]', index: 1 }, function(result) { console.log('getAccessibleName result', result.value); });
browser.getAccessibleName({ selector: '*[name="search"]', timeout: 2000 // overwrite the default timeout (in ms) to check if the element is present }, function(result) { console.log('getAccessibleName result', result.value); }); },
demoTestAsync: async function() { const result = await browser.getAccessibleName('*[name="search"]'); console.log('getAccessibleName result', result); } }
See Also
https://nightwatchjs.org/api/getAccessibleName.html
method getAriaRole
getAriaRole: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>;};
Returns the computed WAI-ARIA role of an element.
Example 1
module.exports = { demoTest(browser) { browser.getAriaRole('*[name="search"]', function(result) { this.assert.equal(typeof result, 'object'); this.assert.equal(result.value, 'combobox'); });
// with explicit locate strategy browser.getAriaRole('css selector', '*[name="search"]', function(result) { console.log('getAriaRole result', result.value); });
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.getAriaRole({ selector: '*[name="search"]', index: 1 }, function(result) { console.log('getAriaRole result', result.value); });
browser.getAriaRole({ selector: '*[name="search"]', timeout: 2000 // overwrite the default timeout (in ms) to check if the element is present }, function(result) { console.log('getAriaRole result', result.value); }); },
demoTestAsync: async function(browser) { const result = await browser.getAriaRole('*[name="search"]'); console.log('getAriaRole result', result); } }
See Also
https://nightwatchjs.org/api/getAriaRole.html
method getAttribute
getAttribute: { ( selector: Definition, attribute: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string | null> ) => void ): Awaitable<this, string | null>; ( using: LocateStrategy, selector: any, attribute: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>;};
Retrieve the value of an attribute for a given DOM element.
Example 1
module.exports = { demoTest() { browser.getAttribute('#main ul li a.first', 'href', function(result) { console.log('result', result); });
// with explicit locate strategy browser.getAttribute('css selector', '#main ul li a.first', 'href', function(result) { console.log('result', result); });
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.getAttribute({ selector: '#main ul li a.first', index: 1, suppressNotFoundErrors: true }, 'href', function(result) { console.log('result', result); }); },
demoTestAsync: async function(browser) { const result = await browser.getAttribute('#main ul li a.first', 'href'); console.log('attribute', result); } }
See Also
https://nightwatchjs.org/api/getAttribute.html
method getCssProperty
getCssProperty: { ( selector: Definition, cssProperty: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>; ( using: LocateStrategy, selector: any, cssProperty: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>;};
Retrieve the value of a css property for a given DOM element.
Example 1
module.exports = { demoTest() { browser.getCssProperty('#main ul li a.first', 'display', function(result) { console.log('result', result); });
// with explicit locate strategy browser.getCssProperty('css selector', '#main ul li a.first', 'display', function(result) { console.log('result', result); });
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.getCssProperty({ selector: '#main ul li a.first', index: 1, suppressNotFoundErrors: true }, 'display', function(result) { console.log('result', result); }); },
demoTestAsync: async function(browser) { const result = await browser.getCssProperty('#main ul li a.first', 'display'); console.log('display', result); } }
See Also
https://nightwatchjs.org/api/getCssProperty.html
method getElementProperty
getElementProperty: { ( selector: Definition, property: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<any> ) => void ): Awaitable<this, any>; ( using: LocateStrategy, selector: any, property: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<any> ) => void ): Awaitable<this, any>;};
Retrieve the value of a specified DOM property for the given element. For all the available DOM element properties, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element).
Example 1
module.exports = { demoTest(browser) { browser.getElementProperty('#login input[type=text]', 'classList', function(result) { console.log('result', result); });
// with explicit locate strategy browser.getElementProperty('css selector', '#login input[type=text]', 'classList', function(result) { console.log('result', result); });
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.getElementProperty({ selector: '#login input[type=text]', index: 1, suppressNotFoundErrors: true }, 'classList', function(result) { console.log('result', result); }); },
demoTestAsync: async function(browser) { const result = await browser.getElementProperty('#login input[type=text]', 'classList'); console.log('classList', result); } }
See Also
https://nightwatchjs.org/api/getElementProperty.html
method getElementRect
getElementRect: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchSizeAndPosition> ) => void ): Awaitable<this, NightwatchSizeAndPosition>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<WindowSizeAndPosition> ) => void ): Awaitable<this, WindowSizeAndPosition>;};
Determine an element's size in pixels. For W3C Webdriver compatible clients (such as GeckoDriver), this command is equivalent to
getLocation
and both return the dimensions and coordinates of the given element: - x: X axis position of the top-left corner of the element, in CSS pixels - y: Y axis position of the top-left corner of the element, in CSS pixels - height: Height of the element’s bounding rectangle in CSS pixels; - width: Width of the web element’s bounding rectangle in CSS pixels.Example 1
module.exports = { demoTest() { browser.getElementSize('#login', function(result) { console.log('result', result); });
// with explicit locate strategy browser.getElementSize('css selector', '#login', function(result) { console.log('result', result); });
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.getElementSize({ selector: '#login', index: 1, suppressNotFoundErrors: true }, function(result) { console.log('result', result); }); },
demoTestAsync: async function() { const result = await browser.getElementSize('#login'); console.log('classList', result); } }
See Also
https://nightwatchjs.org/api/getElementRect.html
method getElementSize
getElementSize: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchSizeAndPosition> ) => void ): Awaitable<this, NightwatchSizeAndPosition>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<WindowSizeAndPosition> ) => void ): Awaitable<this, WindowSizeAndPosition>;};
Determine an element's size in pixels. For W3C Webdriver compatible clients (such as GeckoDriver), this command is equivalent to
getLocation
and both return the dimensions and coordinates of the given element: - x: X axis position of the top-left corner of the element, in CSS pixels - y: Y axis position of the top-left corner of the element, in CSS pixels - height: Height of the element’s bounding rectangle in CSS pixels; - width: Width of the web element’s bounding rectangle in CSS pixels.Example 1
module.exports = { demoTest() { browser.getElementSize('#login', function(result) { console.log('result', result); });
// with explicit locate strategy browser.getElementSize('css selector', '#login', function(result) { console.log('result', result); });
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.getElementSize({ selector: '#login', index: 1, suppressNotFoundErrors: true }, function(result) { console.log('result', result); }); },
demoTestAsync: async function(browser) { const result = await browser.getElementSize('#login'); console.log('classList', result); } }
See Also
https://nightwatchjs.org/api/getElementSize.html
method getFirstElementChild
getFirstElementChild: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<JSON_WEB_OBJECT> ) => void ): Awaitable<this, JSON_WEB_OBJECT>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<JSON_WEB_OBJECT> ) => void ): Awaitable<this, JSON_WEB_OBJECT>;};
Returns an element's first child. The child element will be returned as web element JSON object (with an added .getId() convenience method).
Example 1
module.exports = { 'demo Test': function(browser) { const resultElement = await browser.getFirstElementChild('.features-container');
console.log('last child element Id:', resultElement.getId()); },
See Also
https://nightwatchjs.org/api/getFirstElementChild.html
method getLastElementChild
getLastElementChild: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<JSON_WEB_OBJECT> ) => void ): Awaitable<this, JSON_WEB_OBJECT>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<JSON_WEB_OBJECT> ) => void ): Awaitable<this, JSON_WEB_OBJECT>;};
Returns an element's last child. The child element will be returned as web element JSON object (with an added .getId() convenience method).
Example 1
module.exports = { 'demo Test': function(browser) { const resultElement = await browser.getLastElementChild('.features-container');
console.log('last child element Id:', resultElement.getId()); },
See Also
https://nightwatchjs.org/api/getLastElementChild.html
method getLocation
getLocation: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchSizeAndPosition> ) => void ): Awaitable<this, NightwatchSizeAndPosition>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<WindowSizeAndPosition> ) => void ): Awaitable<this, WindowSizeAndPosition>;};
Determine an element's location on the page. The point (0, 0) refers to the upper-left corner of the page. The element's coordinates are returned as a JSON object with x and y properties.
For W3C Webdriver compatible clients (such as GeckoDriver), this command is equivalent to
getElementSize
and both return the dimensions and coordinates of the given element: - x: X axis position of the top-left corner of the element, in CSS pixels - y: Y axis position of the top-left corner of the element, in CSS pixels - height: Height of the element’s bounding rectangle in CSS pixels; - width: Width of the web element’s bounding rectangle in CSS pixels.Example 1
module.exports = { demoTest() { browser.getLocation('#login', function(result) { console.log('result', result); });
// with explicit locate strategy browser.getLocation('css selector', '#login', function(result) { console.log('result', result); });
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.getLocation({ selector: '#login', index: 1, suppressNotFoundErrors: true }, function(result) { console.log('result', result); }); },
demoTestAsync: async function(browser) { const result = await browser.getLocation('#login'); console.log('location', result); } }
See Also
https://nightwatchjs.org/api/getLocation.html
method getLocationInView
getLocationInView: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchPosition> ) => void ): Awaitable<this, NightwatchPosition>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchPosition> ) => void ): Awaitable<this, NightwatchPosition>;};
Determine an element's location on the screen once it has been scrolled into view.
Example 1
this.demoTest = function () { browser.getLocationInView("#main ul li a.first", function(result) { this.assert.equal(typeof result, "object"); this.assert.equal(result.status, 0); this.assert.equal(result.value.x, 200); this.assert.equal(result.value.y, 200); }); };
See Also
https://nightwatchjs.org/api/getLocationInView.html
Deprecated
This is JSON Wire Protocol command and is no longer supported.
method getNextSibling
getNextSibling: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<JSON_WEB_OBJECT> ) => void ): Awaitable<this, JSON_WEB_OBJECT>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<JSON_WEB_OBJECT> ) => void ): Awaitable<this, JSON_WEB_OBJECT>;};
Returns the element immediately following the specified one in their parent's childNodes. The element will be returned as web element JSON object (with an added .getId() convenience method).
Example 1
module.exports = { 'demo Test': function(browser) { const resultElement = await browser.getNextSibling('.features-container li:first-child');
console.log('next sibling element Id:', resultElement.getId()); },
See Also
https://nightwatchjs.org/api/getNextSibling.html
method getPreviousSibling
getPreviousSibling: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<JSON_WEB_OBJECT> ) => void ): Awaitable<this, JSON_WEB_OBJECT>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<JSON_WEB_OBJECT> ) => void ): Awaitable<this, JSON_WEB_OBJECT>;};
Returns the element immediately preceding the specified one in its parent's child elements list. The element will be returned as web element JSON object (with an added
.getId()
convenience method).Example 1
module.exports = { 'demo Test': function(browser) { const resultElement = await browser.getPreviousSibling('.features-container li:second-child');
console.log('previous sibling element Id:', resultElement.getId()); },
browser.getPreviousSibling('#web-button', function(result) {
console.log(result.value) }}) await browser.getPreviousSibling('#web-button') await browser.getPreviousSibling({selector: '#web-button', locateStrategy: 'css selector'})
// with global element(): const formEl = element('form'); const result = await browser.getPreviousSibling(formEl)
// with Selenium By() locators // https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_By.html const locator = by.tagName('form'); const result = await browser.getPreviousSibling(locator)
// with browser.findElement() const formEl = await browser.findElement('form'); const result = await browser.getPreviousSibling(formEl)
See Also
https://nightwatchjs.org/api/getPreviousSibling.html
method getShadowRoot
getShadowRoot: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ElementGlobal | null> ) => void ): Awaitable<this, ElementGlobal | null>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ElementGlobal> ) => void ): Awaitable<this, ElementGlobal>;};
Returns the
shadowRoot
read-only property which represents the shadow root hosted by the element. This can further be used to retrieve elements part of the shadow root element.Example 1
describe('Shadow Root example test', function() { it('retrieve the shadowRoot', async function(browser) { await browser .navigateTo('https://mdn.github.io/web-components-examples/popup-info-box-web-component/') .waitForElementVisible('form');
const shadowRootEl = await browser.getShadowRoot('popup-info'); const infoElement = await shadowRootEl.find('.info');
await expect(infoElement.property('innerHTML')).to.include('card validation code'); const iconElement = await shadowRootEl.find('.icon'); const firstElement = await browser.getFirstElementChild(iconElement);
await expect.element(firstElement).to.be.an('img'); }); });
See Also
https://nightwatchjs.org/api/getShadowRoot.html
method getTagName
getTagName: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>;};
Query for an element's tag name.
Example 1
module.exports = { demoTest() { browser.getTagName('#login', function(result) { console.log('result', result); });
// with explicit locate strategy browser.getTagName('css selector', '#login', function(result) { console.log('result', result); });
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.getTagName({ selector: '#login', index: 1, suppressNotFoundErrors: true }, function(result) { console.log('result', result); }); },
demoTestAsync: async function(browser) { const result = await browser.getTagName('#login'); console.log('tagName', result); } }
See Also
https://nightwatchjs.org/api/getTagName.html
method getText
getText: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>;};
Returns the visible text for the element.
Example 1
module.exports = { demoTest() { browser.getText('#main ul li a.first', function(result) { this.assert.equal(typeof result, 'object); this.assert.strictEqual(result.status, 0); // only when using Selenium / JSONWire this.assert.equal(result.value, 'nightwatchjs.org'); });
// with explicit locate strategy browser.getText('css selector', '#main ul li a.first', function(result) { console.log('getText result', result.value); });
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.getText({ selector: '#main ul li a', index: 1 }, function(result) { console.log('getText result', result.value); });
browser.getText({ selector: '#main ul li a.first', timeout: 2000 // overwrite the default timeout (in ms) to check if the element is present }, function(result) { console.log('getText result', result.value); }); },
demoTestAsync: async function() { const result = await browser.getText('#main ul li a.first'); console.log('getText result', result); } }
See Also
https://nightwatchjs.org/api/getText.html
method getValue
getValue: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>;};
Returns a form element current value.
Example 1
module.exports = { demoTest() { browser.getValue('#login input[type=text]', function(result) { console.log('result', result); });
// with explicit locate strategy browser.getValue('css selector', '#login input[type=text]', function(result) { console.log('result', result); });
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.getValue({ selector: '#login input[type=text]', index: 1, suppressNotFoundErrors: true }, function(result) { console.log('result', result); }); },
demoTestAsync: async function() { const result = await browser.getValue('#login input[type=text]'); console.log('Value', result); } }
See Also
https://nightwatchjs.org/api/getValue.html
method hasDescendants
hasDescendants: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void ): Awaitable<this, boolean>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void ): Awaitable<this, boolean>;};
Returns true or false based on whether the DOM has any child nodes
Example 1
module.exports = { 'demo Test': function(browser) { const result = await browser.hasDescendants('.features-container');
console.log('true or false:', result); },
See Also
https://nightwatchjs.org/api/hasDescendants.html
method isEnabled
isEnabled: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void ): Awaitable<this, boolean>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void ): Awaitable<this, boolean>;};
Determines if an element is enabled, as indicated by the 'disabled' attribute.
Example 1
module.exports = { demoTest(browser) { browser.isEnabled('#main select option.first', function(result) { this.assert.equal(typeof result, "object"); this.assert.equal(result.status, 0); this.assert.equal(result.value, true); });
// with explicit locate strategy browser.isEnabled('css selector', '#main select option.first');
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.isEnabled({ selector: '#main ul li a', index: 1, suppressNotFoundErrors: true });
browser.isEnabled({ selector: '#main select option.first', timeout: 2000 // overwrite the default timeout (in ms) to check if the element is present }); },
demoTestAsync: async function(browser) { const result = await browser.isEnabled('#main select option.first'); console.log('isVisible result', result); } }
See Also
https://nightwatchjs.org/api/isEnabled.html
method isPresent
isPresent: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void ): Awaitable<this, boolean>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void ): Awaitable<this, boolean>;};
Determines if an element is present in the DOM.
Example 1
module.exports = { demoTest(browser) { browser.isPresent('#main ul li a.first', function(result) { this.assert.equal(typeof result, "object"); this.assert.equal(result.status, 0); this.assert.equal(result.value, true); });
// with explicit locate strategy browser.isPresent('css selector', '#main ul li a.first');
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.isPresent({ selector: '#main ul li a', index: 1, });
browser.isPresent({ selector: '#main ul li a.first', timeout: 2000 // overwrite the default timeout (in ms) to check if the element is present }); },
demoTestAsync: async function(browser) { const result = await browser.isPresent('#main ul li a.first'); console.log('isPresent result', result); } }
See Also
https://nightwatchjs.org/api/isPresent.html
method isSelected
isSelected: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void ): Awaitable<this, boolean>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void ): Awaitable<this, boolean>;};
Determines if an element is selected.
Example 1
module.exports = { demoTest(browser) { browser.isSelected('#main select option.first', function(result) { this.assert.equal(typeof result, "object"); this.assert.equal(result.status, 0); this.assert.equal(result.value, true); });
// with explicit locate strategy browser.isSelected('css selector', '#main select option.first');
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.isSelected({ selector: '#main ul li a', index: 1, suppressNotFoundErrors: true });
browser.isSelected({ selector: '#main select option.first', timeout: 2000 // overwrite the default timeout (in ms) to check if the element is present }); },
demoTestAsync: async function(browser) { const result = await browser.isSelected('#main select option.first'); console.log('isVisible result', result); } }
See Also
https://nightwatchjs.org/api/isSelected.html
method isVisible
isVisible: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void ): Awaitable<this, boolean>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void ): Awaitable<this, boolean>;};
Determine if an element is currently displayed.
Example 1
module.exports = { demoTest() { browser.isVisible('#main ul li a.first', function(result) { this.assert.equal(typeof result, "object"); this.assert.equal(result.status, 0); this.assert.equal(result.value, true); });
// with explicit locate strategy browser.isVisible('css selector', '#main ul li a.first');
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.isVisible({ selector: '#main ul li a', index: 1, suppressNotFoundErrors: true });
browser.isVisible({ selector: '#main ul li a.first', timeout: 2000 // overwrite the default timeout (in ms) to check if the element is present }); },
demoTestAsync: async function() { const result = await browser.isVisible('#main ul li a.first'); console.log('isVisible result', result); } }
See Also
https://nightwatchjs.org/api/isVisible.html
method moveToElement
moveToElement: { ( selector: Definition, xoffset: number, yoffset: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( using: LocateStrategy, selector: any, xoffset: number, yoffset: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Move the mouse by an offset of the specified element. If an element is provided but no offset, the mouse will be moved to the center of the element. If the element is not visible, it will be scrolled into view.
Example 1
this.demoTest = function () { browser.moveToElement('#main', 10, 10); };
See Also
https://nightwatchjs.org/api/moveToElement.html
method rightClick
rightClick: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Simulates a context-click(right click) event on the given DOM element. The element is scrolled into view if it is not already pointer-interactable. See the WebDriver specification for element [interactability](https://www.w3.org/TR/webdriver/#element-interactability).
Example 1
module.exports = { demoTest() { browser.rightClick('#main ul li a.first');
browser.rightClick('#main ul li a.first', function(result) { console.log('Click result', result); });
// with explicit locate strategy browser.rightClick('css selector', '#main ul li a.first');
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.rightClick({ selector: '#main ul li a', index: 1, suppressNotFoundErrors: true });
browser.rightClick({ selector: '#main ul li a.first', timeout: 2000 // overwrite the default timeout (in ms) to check if the element is present }); },
demoTestAsync: async function() { const result = await browser.rightClick('#main ul li a.first'); console.log('Right click result', result); } }
See Also
https://nightwatchjs.org/api/rightClick.html#apimethod-container
method sendKeys
sendKeys: { ( selector: Definition, inputValue: string | string[], callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( using: LocateStrategy, selector: any, inputValue: string | string[], callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Types a key sequence on the DOM element. Can be used to send a sequence of key strokes to an element. Any UTF-8 character may be specified.
**sendKeys** does not clear the existing value of the element. To do so, use **setValue()** instead.
An object map with available keys and their respective UTF-8 characters, as defined on [W3C WebDriver draft spec](https://www.w3.org/TR/webdriver/#character-types), is loaded onto the main Nightwatch instance as
browser.Keys
.Example 1
// send some simple text to an input this.demoTest = function () { browser.sendKeys('input[type=text]', 'nightwatch'); }; // // send some text to an input and hit enter. this.demoTest = function () { browser.sendKeys('input[type=text]', ['nightwatch', browser.Keys.ENTER]); };
See Also
https://nightwatchjs.org/api/sendKeys.html
method setAttribute
setAttribute: { ( selector: Definition, attribute: string, value: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void ): Awaitable<this, boolean>; ( using: LocateStrategy, selector: any, attribute: string, value: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void ): Awaitable<this, boolean>;};
Set the value of a specified DOM attribute for the given element. For all the available DOM attributes, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element).
Example 1
module.exports = { demoTest(browser) { browser.setAttribute('#login input[type=text]', 'disabled', 'true', function(result) { console.log('result', result); });
// with explicit locate strategy browser.setAttribute('css selector', '#login input[type=text]', 'disabled', 'true', function(result) { console.log('result', result); });
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.setAttribute({ selector: '#login input[type=text]', index: 1, suppressNotFoundErrors: true }, 'disabled', 'true', function(result) { console.log('result', result); }); },
demoTestAsync: async function(browser) { await browser.setAttribute('#login input[type=text]', 'disabled', 'true'); } }
See Also
https://nightwatchjs.org/api/setAttribute.html
method setPassword
setPassword: { ( selector: Definition, inputValue: string | string[], callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( using: LocateStrategy, selector: any, inputValue: string | string[], callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
An alias of "setValue" command, but hides the content from the nightwatch logs.
setValue/setPassword do not clear the existing value of the element. To do so, use the clearValue() command.
An object map with available keys and their respective UTF-8 characters, as defined on [W3C WebDriver draft spec](https://www.w3.org/TR/webdriver/#character-types), is loaded onto the main Nightwatch instance as
browser.Keys
.Example 1
// send some simple text to an input this.demoTest = function (browser) { browser.setPassword('input[type=text]', 'nightwatch'); }; // // send some text to an input and hit enter. this.demoTest = function (browser) { browser.setPassword('input[type=text]', ['nightwatch', browser.Keys.ENTER]); };
method setValue
setValue: { ( selector: Definition, inputValue: string | string[], callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( using: LocateStrategy, selector: any, inputValue: string | string[], callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Sends some text to an element. Can be used to set the value of a form element or to send a sequence of key strokes to an element. Any UTF-8 character may be specified.
From Nightwatch v2, **setValue** also clears the existing value of the element by calling the **clearValue()** beforehand.
An object map with available keys and their respective UTF-8 characters, as defined on [W3C WebDriver draft spec](https://www.w3.org/TR/webdriver/#character-types), is loaded onto the main Nightwatch instance as
browser.Keys
.Example 1
// send some simple text to an input this.demoTest = function () { browser.setValue('input[type=text]', 'nightwatch'); }; // // send some text to an input and hit enter. this.demoTest = function () { browser.setValue('input[type=text]', ['nightwatch', browser.Keys.ENTER]); };
See Also
https://nightwatchjs.org/api/setValue.html
method submitForm
submitForm: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Submit a FORM element. The submit command may also be applied to any element that is a descendant of a FORM element. Uses
submit
protocol command.Example 1
this.demoTest = function () { browser.submitForm('form.login'); };
See Also
https://nightwatchjs.org/api/submitForm.html
method takeElementScreenshot
takeElementScreenshot: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>;};
Take a screenshot of the visible region encompassed by this element's bounding rectangle.
Example 1
module.exports = { demoTest(browser) { browser.takeElementScreenshot('#main', function (imageData, err) { require('fs').writeFile('out.png', imageData.value, 'base64', function (err) { console.log(err); }); });
// with explicit locate strategy browser.takeElementScreenshot('css selector', '#main', function(imageData, err) { require('fs').writeFile('out.png', imageData.value, 'base64', function (err) { console.log(err); }); });
// with selector object - see https://nightwatchjs.org/guide/writing-tests/finding-interacting-with-dom-elements.html#postdoc-element-properties browser.takeElementScreenshot({ selector: '#main ul li a', index: 1 }, function(imageData, err) { require('fs').writeFile('out.png', imageData.value, 'base64', function (err) { console.log(err); }); }); },
demoTestAsync: async function(browser) { const data = await browser.takeElementScreenshot('#main'); require('fs').writeFile('out.png', data, 'base64'); } }
See Also
https://nightwatchjs.org/api/takeElementScreenshot.html
method uncheck
uncheck: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Will uncheck, click, on a checked checkbox or radio input if not already unchecked.
Example 1
module.exports = { demoTest(browser) { browser.uncheck('input[type=checkbox]:checked)');
browser.uncheck('input[type=checkbox]:checked)', function(result) { console.log('Check result', result); });
// with explicit locate strategy browser.uncheck('css selector', 'input[type=checkbox]:checked)');
// with selector object - see https://nightwatchjs.org/guide#element-properties browser.uncheck({ selector: 'input[type=checkbox]:checked)', index: 1, suppressNotFoundErrors: true });
browser.uncheck({ selector: 'input[type=checkbox]:checked)', timeout: 2000 // overwrite the default timeout (in ms) to check if the element is present }); },
demoTestAsync: async function(browser) { const result = await browser.uncheck('input[type=checkbox]:checked)'); console.log('Check result', result); } }
Will uncheck, click, on a checked checkbox or radio input if not already unchecked.
See Also
https://nightwatchjs.org/api/uncheck.html
method updateValue
updateValue: { ( selector: Definition, inputValue: string | string[], callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( using: LocateStrategy, selector: any, inputValue: string | string[], callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Sends some text to an element. Can be used to set the value of a form element or to send a sequence of key strokes to an element. Any UTF-8 character may be specified.
updateValue is equivalent with setValue and sendKeys with the exception that it clears the value beforehand.
An object map with available keys and their respective UTF-8 characters, as defined on [W3C WebDriver draft spec](https://www.w3.org/TR/webdriver/#character-types), is loaded onto the main Nightwatch instance as
browser.Keys
.Example 1
// send some simple text to an input this.demoTest = function (browser) { browser.updateValue('input[type=text]', 'nightwatch'); };
// send some text to an input and hit enter. this.demoTest = function (browser) { browser.updateValue('input[type=text]', ['nightwatch', browser.Keys.ENTER]); };
See Also
https://nightwatchjs.org/api/updateValue.html
method uploadFile
uploadFile: { ( selector: Definition, filePath: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( using: LocateStrategy, selector: any, filePath: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Uploads file to an element using absolute file path.
Example 1
// send a file to for upload to a field. this.demoTest = function (browser) { browser.uploadFile('#myFile', '/path/file.pdf'); };
See Also
https://nightwatchjs.org/api/uploadFile.html
method waitForElementNotPresent
waitForElementNotPresent: { ( selector: Definition, timeoutOrCallbackOrMessage?: | number | NightwatchGenericCallback<null | ElementResult[]> | string, pollIntervalOrAbortOnFailureOrCallbackOrMessage?: | number | boolean | NightwatchGenericCallback<null | ElementResult[]> | string, abortOnFailureOrCallbackOrMessage?: | boolean | NightwatchGenericCallback<null | ElementResult[]> | string, callbackOrMessage?: | NightwatchGenericCallback<null | ElementResult[]> | string, message?: string ): Awaitable<this, null | Error>; ( using: LocateStrategy, selector: any, timeoutOrCallbackOrMessage?: | string | number | NightwatchGenericCallback<ElementResult[]>, pollIntervalOrAbortOnFailureOrCallbackOrMessage?: | string | number | boolean | NightwatchGenericCallback<ElementResult[]>, abortOnFailureOrCallbackOrMessage?: | string | boolean | NightwatchGenericCallback<ElementResult[]>, callbackOrMessage?: string | NightwatchGenericCallback<ElementResult[]>, message?: string ): Awaitable<this, Error>;};
Opposite of
waitForElementPresent
. Waits a given time in milliseconds (default 5000ms) for an element to be not present (i.e. removed) in the page before performing any other commands or assertions. If the element is still present after the specified amount of time, the test fails.You can change the polling interval by defining a
waitForConditionPollInterval
property (in milliseconds) in as a global property in yournightwatch.json
or in your external globals file. Similarly, a default timeout can be specified as a globalwaitForConditionTimeout
property (in milliseconds).Returns
null
if element not found,Error
otherwise.Example 1
// 'message' should always be the last argument (if provided). // 'callback' should only be second-last to the 'message' argument, otherwise always last. module.exports = { 'demo Test': function() { // with default implicit timeout of 5000ms (can be overwritten in settings under 'globals.waitForConditionTimeout') browser.waitForElementNotPresent('#dialog');
// specify the locate strategy (css selector/xpath) as the first argument browser.waitForElementNotPresent('css selector', '#dialog');
// with explicit timeout (in milliseconds) browser.waitForElementNotPresent('#dialog', 1000);
// continue if failed browser.waitForElementNotPresent('#dialog', 1000, false);
// with callback browser.waitForElementNotPresent('#dialog', 1000, function() { // do something while we're here });
// with custom output message - the locate strategy is required browser.waitForElementNotPresent('css selector', '#dialog', 'The dialog container is removed.');
// with custom Spanish message browser.waitForElementNotPresent('#dialog', 1000, 'elemento %s no era presente en %d ms');
// many combinations possible - the message is always the last argument browser.waitForElementNotPresent('#dialog', 1000, false, function() {}, 'elemento %s no era presente en %d ms'); },
'demo Test with selector objects': function() { browser.waitForElementNotPresent({ selector: '#dialog', timeout: 1000 });
browser.waitForElementNotPresent({ selector: '#dialog', locateStrategy: 'css selector' }, 'Custom output message');
browser.waitForElementNotPresent({ selector: '.container', index: 2, retryInterval: 100, abortOnFailure: true }); }
'page object demo Test': function () { var nightwatch = browser.page.nightwatch(); nightwatch .navigate() .assert.titleContains('Nightwatch.js');
nightwatch.waitForElementNotPresent('@dialogContainer', function(result) { console.log(result); }); } }
See Also
https://nightwatchjs.org/api/waitForElementNotPresent.html v0.4.0
method waitForElementNotVisible
waitForElementNotVisible: { ( selector: Definition, timeoutOrCallbackOrMessage?: | number | NightwatchGenericCallback<boolean> | string, pollIntervalOrAbortOnFailureOrCallbackOrMessage?: | number | boolean | NightwatchGenericCallback<boolean> | string, abortOnFailureOrCallbackOrMessage?: | boolean | NightwatchGenericCallback<boolean> | string, callbackOrMessage?: NightwatchGenericCallback<boolean> | string, message?: string ): Awaitable<this, false | Error>; ( using: LocateStrategy, selector: any, timeoutOrCallbackOrMessage?: | string | number | NightwatchGenericCallback<boolean>, pollIntervalOrAbortOnFailureOrCallbackOrMessage?: | string | number | boolean | NightwatchGenericCallback<boolean>, abortOnFailureOrCallbackOrMessage?: | string | boolean | NightwatchGenericCallback<boolean>, callbackOrMessage?: string | NightwatchGenericCallback<boolean>, message?: string ): Awaitable<this, false | Error>;};
Opposite of
waitForElementVisible
. Waits a given time in milliseconds (default 5000ms) for an element to be not visible (i.e. hidden but existing) in the page before performing any other commands or assertions. If the element fails to be hidden in the specified amount of time, the test fails.You can change the polling interval by defining a
waitForConditionPollInterval
property (in milliseconds) in as a global property in yournightwatch.json
or in your external globals file. Similarly, a default timeout can be specified as a globalwaitForConditionTimeout
property (in milliseconds).Returns
false
if element not visible,Error
otherwise.Example 1
// 'message' should always be the last argument (if provided). // 'callback' should only be second-last to the 'message' argument, otherwise always last. module.exports = { 'demo Test': function() { // with default implicit timeout of 5000ms (can be overwritten in settings under 'globals.waitForConditionTimeout') browser.waitForElementNotVisible('#dialog');
// specify the locate strategy (css selector/xpath) as the first argument browser.waitForElementNotVisible('css selector', '#dialog');
// with explicit timeout (in milliseconds) browser.waitForElementNotVisible('#dialog', 1000);
// continue if failed browser.waitForElementNotVisible('#dialog', 1000, false);
// with callback browser.waitForElementNotVisible('#dialog', 1000, function() { // do something while we're here });
// with custom output message - the locate strategy is required browser.waitForElementNotVisible('css selector', '#dialog', 'The dialog container is not visible.');
// with custom Spanish message browser.waitForElementNotVisible('#dialog', 1000, 'elemento %s no era visible en %d ms');
// many combinations possible - the message is always the last argument browser.waitForElementNotVisible('#dialog', 1000, false, function() {}, 'elemento %s no era visible en %d ms'); },
'demo Test with selector objects': function() { browser.waitForElementNotVisible({ selector: '#dialog', timeout: 1000 });
browser.waitForElementNotVisible({ selector: '#dialog', locateStrategy: 'css selector' }, 'Custom output message');
browser.waitForElementNotVisible({ selector: '.container', index: 2, retryInterval: 100, abortOnFailure: true }); }
'page object demo Test': function () { var nightwatch = browser.page.nightwatch(); nightwatch .navigate() .assert.titleContains('Nightwatch.js');
nightwatch.waitForElementNotVisible('@mainDialog', function(result) { console.log(result); }); } }
v0.4.0
See Also
https://nightwatchjs.org/api/waitForElementNotVisible.html
method waitForElementPresent
waitForElementPresent: { ( selector: Definition, timeoutOrCallbackOrMessage?: | number | NightwatchGenericCallback<null | ElementResult[]> | string, pollIntervalOrAbortOnFailureOrCallbackOrMessage?: | number | boolean | NightwatchGenericCallback<null | ElementResult[]> | string, abortOnFailureOrCallbackOrMessage?: | boolean | NightwatchGenericCallback<null | ElementResult[]> | string, callbackOrMessage?: | NightwatchGenericCallback<null | ElementResult[]> | string, message?: string ): Awaitable<this, ElementResult[] | Error>; ( using: LocateStrategy, selector: any, timeoutOrCallbackOrMessage?: | string | number | NightwatchGenericCallback<ElementResult[]>, pollIntervalOrAbortOnFailureOrCallbackOrMessage?: | string | number | boolean | NightwatchGenericCallback<ElementResult[]>, abortOnFailureOrCallbackOrMessage?: | string | boolean | NightwatchGenericCallback<ElementResult[]>, callbackOrMessage?: string | NightwatchGenericCallback<ElementResult[]>, message?: string ): Awaitable<this, Error | ElementResult[]>;};
Waits a given time in milliseconds (default 5000ms) for an element to be present in the page before performing any other commands or assertions. If the element fails to be present in the specified amount of time, the test fails. You can change this by setting
abortOnFailure
tofalse
.You can change the polling interval by defining a
waitForConditionPollInterval
property (in milliseconds) in as a global property in yournightwatch.json
or in your external globals file. Similarly, the default timeout can be specified as a globalwaitForConditionTimeout
property (in milliseconds).Returns
ElementResult[]
if element is found,Error
otherwise.Example 1
// 'message' should always be the last argument (if provided). // 'callback' should only be second-last to the 'message' argument, otherwise always last. module.exports = { 'demo Test': function() { // with default implicit timeout of 5000ms (can be overwritten in settings under 'globals.waitForConditionTimeout') browser.waitForElementPresent('#index-container');
// specify the locate strategy (css selector/xpath) as the first argument browser.waitForElementPresent('css selector', '#index-container');
// with explicit timeout (in milliseconds) browser.waitForElementPresent('#index-container', 1000);
// continue if failed browser.waitForElementPresent('#index-container', 1000, false);
// with callback browser.waitForElementPresent('#index-container', 1000, function() { // do something while we're here });
// with custom output message - the locate strategy is required browser.waitForElementPresent('css selector', '#index-container', 'The index container is found.');
// with custom Spanish message browser.waitForElementPresent('#index-container', 1000, 'elemento %s no era presente en %d ms');
// many combinations possible - the message is always the last argument browser.waitForElementPresent('#index-container', 1000, false, function() {}, 'elemento %s no era presente en %d ms'); },
'demo Test with selector objects': function() { browser.waitForElementPresent({ selector: '#index-container', timeout: 1000 });
browser.waitForElementPresent({ selector: '#index-container', locateStrategy: 'css selector' }, 'Custom output message');
browser.waitForElementPresent({ selector: '.container', index: 2, retryInterval: 100, abortOnFailure: true }); }
'page object demo Test': function () { var nightwatch = browser.page.nightwatch(); nightwatch .navigate() .assert.titleContains('Nightwatch.js');
nightwatch.waitForElementPresent('@featuresList', function(result) { console.log(result); }); } }
See Also
https://nightwatchjs.org/api/waitForElementPresent.html
method waitForElementVisible
waitForElementVisible: { ( selector: Definition, timeoutOrCallbackOrMessage?: | number | NightwatchGenericCallback<boolean> | string, pollIntervalOrAbortOnFailureOrCallbackOrMessage?: | number | boolean | NightwatchGenericCallback<boolean> | string, abortOnFailureOrCallbackOrMessage?: | boolean | NightwatchGenericCallback<boolean> | string, callbackOrMessage?: NightwatchGenericCallback<boolean> | string, message?: string ): Awaitable<this, true | Error>; ( using: LocateStrategy, selector: any, timeoutOrCallbackOrMessage?: | string | number | NightwatchGenericCallback<boolean>, pollIntervalOrAbortOnFailureOrCallbackOrMessage?: | string | number | boolean | NightwatchGenericCallback<boolean>, abortOnFailureOrCallbackOrMessage?: | string | boolean | NightwatchGenericCallback<boolean>, callbackOrMessage?: string | NightwatchGenericCallback<boolean>, message?: string ): Awaitable<this, true | Error>;};
Waits a given time in milliseconds for an element to be visible in the page before performing any other commands or assertions.
If the element fails to be present and visible in the specified amount of time, the test fails. You can change this by setting
abortOnFailure
tofalse
.You can change the polling interval by defining a
waitForConditionPollInterval
property (in milliseconds) in as a global property in yournightwatch.json
or in your external globals file.Similarly, a default timeout can be specified as a global
waitForConditionTimeout
property (in milliseconds).Returns
true
is element is visible,Error
otherwise.Example 1
// 'message' should always be the last argument (if provided). // 'callback' should only be second-last to the 'message' argument, otherwise always last. this.demoTest = function (browser) { browser.waitForElementVisible('body', 1000); // continue if failed browser.waitForElementVisible('body', 1000, false); // with callback browser.waitForElementVisible('body', 1000, function() { // do something while we're here }); // custom Spanish message browser.waitForElementVisible('body', 1000, 'elemento %s no era visible en %d ms'); // many combinations possible - the message is always the last argument browser.waitForElementVisible('body', 1000, false, function() {}, 'elemento %s no era visible en %d ms'); };
See Also
https://nightwatchjs.org/api/waitForElementVisible.html
interface ElementFunction
interface ElementFunction extends Pick< ScopedElement, | 'find' | 'get' | 'findElement' | 'findByText' | 'findByRole' | 'findByPlaceholderText' | 'findByLabelText' | 'findByAltText' | 'findAll' | 'getAll' | 'findElements' | 'findAllByText' | 'findAllByRole' | 'findAllByPlaceholderText' | 'findAllByAltText' > {}
method findActive
findActive: () => ScopedElement;
call signature
(selector: ScopedElementSelector): ScopedElement;
call signature
( using: LocateStrategy, value: string, callback?: (result: never) => void): ScopedElement;
interface ElementGlobal
interface ElementGlobal extends Element {}
property accessibleName
accessibleName: ElementGlobal['getAccessibleName'];
Get the computed WAI-ARIA label of element.
property ariaRole
ariaRole: ElementGlobal['getAriaRole'];
Get the computed WAI-ARIA role of element.
property attr
attr: ElementGlobal['getAttribute'];
Retrieves the current value of the given attribute of this element.
See Also
https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html#getAttribute
property attribute
attribute: ElementGlobal['getAttribute'];
Retrieves the current value of the given attribute of this element.
See Also
https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html#getAttribute
property css
css: ElementGlobal['getCssValue'];
Retrieves the value of a computed style property for this instance.
See Also
https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html#getCssValue
property element
element: ElementGlobal['find'];
property get
get: ElementGlobal['find'];
property isComponent
isComponent?: boolean;
property prop
prop: ElementGlobal['getProperty'];
Retrieves the value of the given property of this element.
property property
property: ElementGlobal['getProperty'];
Retrieves the value of the given property of this element.
property rect
rect: ElementGlobal['getRect'];
Returns an object describing an element's location, in pixels relative to the document element, and the element's size in pixels.
property screenshot
screenshot: ElementGlobal['takeScreenshot'];
Take a screenshot of the visible region encompassed by this element's bounding rectangle.
property tagName
tagName: ElementGlobal['getTagName'];
Retrieves the element's tag name.
property text
text: ElementGlobal['getText'];
Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.
method clear
clear: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<NightwatchAPI, null>;
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 Also
https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html#clear
method click
click: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<NightwatchAPI, null>;
Clicks on this element.
See Also
https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html#click
method find
find: { (): Awaitable<NightwatchAPI, WebElement>; ( selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ElementGlobal> ) => void ): Awaitable<NightwatchAPI, ElementGlobal>;};
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.
method findAll
findAll: ( selector: ElementGlobalDefinition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ElementGlobal[]> ) => void) => Awaitable<NightwatchAPI, ElementGlobal[]>;
method findElement
findElement: { (): Awaitable<NightwatchAPI, WebElement>; ( selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<WebElement> ) => void ): Awaitable<NightwatchAPI, WebElement>;};
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.
method findElements
findElements: ( selector: ElementGlobalDefinition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<WebElement[]> ) => void) => Awaitable<NightwatchAPI, WebElement[]>;
Locates all of the descendants of this element that match the given search criteria.
method getAccessibleName
getAccessibleName: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<NightwatchAPI, string>;
Get the computed WAI-ARIA label of element.
method getAriaRole
getAriaRole: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<NightwatchAPI, string>;
Get the computed WAI-ARIA role of element.
method 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 Also
https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html#getAttribute
method 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 Also
https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html#getCssValue
method getId
getId: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<NightwatchAPI, string>;
Get the server-assigned opaque ID assigned to this element.
method getProperty
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.
method getRect
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.
method getTagName
getTagName: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<NightwatchAPI, string>;
Retrieves the element's tag name.
method getText
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.
method getWebElement
getWebElement: () => Awaitable<NightwatchAPI, WebElement>;
Get the [WebElement](https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html) instance for this element.
method isDisplayed
isDisplayed: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void) => Awaitable<NightwatchAPI, boolean>;
Test whether this element is currently displayed.
method isEnabled
isEnabled: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void) => Awaitable<NightwatchAPI, boolean>;
Tests whether this element is enabled, as dictated by the
disabled
attribute.
method isSelected
isSelected: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void) => Awaitable<NightwatchAPI, boolean>;
Tests whether this element is selected.
method sendKeys
sendKeys: ( ...args: Array<string | number | PromiseLike<string> | PromiseLike<number>>) => Awaitable<NightwatchAPI, null>;
Types a key sequence on the DOM element represented by this instance.
Example 1
element().sendKeys(1, 'something', browser.Keys.SPACE, Promise.resolve(2));
See Also
https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html#sendKeys
method submit
submit: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => 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 Also
https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html#submit
method takeScreenshot
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.
interface ElementProperties
interface ElementProperties {}
property abortOnFailure
abortOnFailure?: boolean;
used to overwrite this setting when using waitForElement* commands.
property index
index?: number;
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.
property locateStrategy
locateStrategy?: LocateStrategy;
locator strategy can be one of - css selector - link text - partial link text - tag name - xpath
Example 1
'css selector'
property retryInterval
retryInterval?: number;
used to overwrite the default retry interval for when using waitForElement* commands or assertions.
property selector
selector: string;
the element selector name
Example 1
'@searchBar'
property suppressNotFoundErrors
suppressNotFoundErrors?: boolean;
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.
property timeout
timeout?: number;
used to overwrite the default timeout for when using waitForElement* commands or assertions.
interface ElementResult
interface ElementResult {}
property [ELEMENT_KEY]
[ELEMENT_KEY]: string;
interface EnhancedElementInstance
interface EnhancedElementInstance<T> {}
#### [Enhanced Element Instances](https://github.com/nightwatchjs/nightwatch/wiki/Page-Object-API#enhanced-element-instances) Element instances encapsulate the definition used to handle element selectors. Generally you won't need to access them directly, instead referring to them using their
@
-prefixed names for selector arguments, but they are available through a page object or section's elements property.
property locateStrategy
locateStrategy: LocateStrategy;
The locate strategy to be used with
selector
when finding the element within the DOM.
property name
name: string;
The name of the element as defined by its key in the parent section or the page object's
elements
definition. This is the same name used with the@
prefix in selector arguments for page object commands that refer to the element.
property parent
parent: T;
A reference to the parent object instance. This is the parent section or the page object that contained the definition for this object.
property selector
selector: string;
The selector string used to find the element in the DOM.
interface EnhancedPageObjectSections
interface EnhancedPageObjectSections< Commands = {}, Elements = {}, Sections extends Record<string, PageObjectSection> = {}, Props = {}, Parent = unknown> extends EnhancedPageObjectSharedFields<Commands, Elements, Sections, Props> {}
property locateStrategy
locateStrategy: LocateStrategy;
The locate strategy used with
selector
when finding the section within the DOM. - css selector - link text - partial link text - tag name - xpathExample 1
'css selector'
property parent
parent: Parent;
Parent of the section.
property selector
selector: string;
The selector string used to find the section in the DOM.
Example 1
'#searchBar'
interface EnhancedPageObjectSharedFields
interface EnhancedPageObjectSharedFields< Commands = {}, Elements = {}, Sections extends Record<string, PageObjectSection> = {}, Props = {}, URL = string> {}
property alerts
alerts: AlertsNsCommands<this>;
property api
api: NightwatchAPI;
Nightwatch API.
property assert
assert: Assert<this>;
property client
client: NightwatchClient;
Nightwatch Client.
property cookies
cookies: CookiesNsCommands<this>;
property document
document: DocumentNsCommands<this>;
property element
element: ElementFunction;
Nightwatch new element API.
property elements
elements: { [key in keyof Elements]: EnhancedElementInstance< EnhancedPageObject<Commands, Elements, Sections, Props, URL> >;};
A map of Element objects (see [Enhanced Element Instances](https://github.com/nightwatchjs/nightwatch/wiki/Page-Object-API#enhanced-element-instances)) used by element selectors.
property expect
expect: Expect;
property name
name: string;
The name of the page object as defined by its module name (not including the extension). This is the same name used to access the
page
object factory from the page reference in the command API.
property props
props: Props;
An object or a function returning an object representing a container for user variables.
property section
section: { [Key in keyof Sections]: EnhancedSectionInstance< Required<MergeObjectsArray<Sections[Key]['commands']>>, Required<MergeObjectsArray<Sections[Key]['elements']>>, Required<Sections[Key]['sections']>, Required<Sections[Key]['props']>, this >;};
Section object (see [Enhanced Element Instances](https://github.com/nightwatchjs/nightwatch/wiki/Page-Object-API#enhanced-section-instances))
property verify
verify: Assert<this>;
interface Ensure
interface Ensure {}
method ableToSwitchToFrame
ableToSwitchToFrame: ( frame: number | WebElement | SeleniumBy) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Ensures that the Nightwatch WebDriver client is able to switch to the designated frame.
method alertIsPresent
alertIsPresent: () => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that waits for an alert to be opened.
method elementIsDisabled
elementIsDisabled: ( element: WebElement | Element | string) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the given element to be disabled.
method elementIsEnabled
elementIsEnabled: ( element: WebElement) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the given element to be enabled.
method elementIsNotSelected
elementIsNotSelected: ( element: WebElement | Element | string) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the given element to be deselected.
method elementIsNotVisible
elementIsNotVisible: ( 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.
method elementIsSelected
elementIsSelected: ( element: WebElement | Element | string) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the given element to be selected.
method elementIsVisible
elementIsVisible: ( element: WebElement | Element | string) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the given element to be displayed.
method elementLocated
elementLocated: ( locator: SeleniumBy) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will loop until an element is found with the given locator.
method elementsLocated
elementsLocated: ( locator: SeleniumBy) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will loop until at least one element is found with the given locator.
method elementTextContains
elementTextContains: ( element: WebElement | Element | string, substr: string) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the given element's text to contain the given substring.
method elementTextIs
elementTextIs: ( element: WebElement | Element | string, text: string) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the given element's text to equal the given text.
method elementTextMatches
elementTextMatches: ( element: WebElement | Element | string, regex: RegExp) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the given element's text to match a given regular expression.
method stalenessOf
stalenessOf: ( element: WebElement | Element | string) => 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.
method titleContains
titleContains: ( substr: string) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the current page's title to contain the given substring.
method titleIs
titleIs: (title: string) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the current page's title to match the given value.
method titleMatches
titleMatches: ( regex: RegExp) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the current page's title to match the given regular expression.
method urlContains
urlContains: ( substrUrl: string) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the current page's url to contain the given substring.
method urlIs
urlIs: (url: string) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the current page's url to match the given value.
method urlMatches
urlMatches: (regex: RegExp) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the current page's url to match the given regular expression.
interface Expect
interface Expect {}
method component
component: (property: Definition) => ExpectElement;
Expect assertions operating on a single component.
method cookie
cookie: (name: string, domain?: string) => ExpectCookie;
Expect assertions operating on a single cookie after retrieving the entire cookie string, using .getCookies().
method element
element: (property: Definition) => ExpectElement;
Expect assertions operating on a single element, specified by its CSS/Xpath selector.
method elements
elements: (property: ScopedSelector) => ExpectElements;
Expect assertions operating on a collection of elements, specified by a CSS/Xpath selector. So far only .count is available.
method section
section: (property: ScopedSelector) => ExpectSection;
Expect assertions operating on a page-object section, specified by '
@section_name
'.
method title
title: () => ExpectTitle;
Retrieves the page title value in order to be used for performing equal, match or contains assertions on it.
method url
url: () => ExpectUrl;
Retrieves the page url value in order to be used for performing equal, match or contains assertions on it.
call signature
(val: Element | WebElement | By | { [ELEMENT_KEY]: string }): ExpectElement;
call signature
(val: any): Chai.Assertion;
interface ExpectAssertions
interface ExpectAssertions<T> extends ExpectLanguageChains<T> {}
property after
after: (ms: number) => Awaitable<T, NightwatchExpectResult>;
property before
before: (ms: number) => Awaitable<T, NightwatchExpectResult>;
property contain
contain: ExpectInclude<T>;
property contains
contains: ExpectInclude<T>;
property endsWith
endsWith: ExpectEndWith<T>;
property endWith
endWith: ExpectEndWith<T>;
property eq
eq: ExpectEqual<T>;
property equal
equal: ExpectEqual<T>;
property equals
equals: ExpectEqual<T>;
property include
include: ExpectInclude<T>;
property includes
includes: ExpectInclude<T>;
property match
match: ExpectMatch<T>;
property matches
matches: ExpectMatch<T>;
property startsWith
startsWith: ExpectStartWith<T>;
property startWith
startWith: ExpectStartWith<T>;
property toBe
toBe: (value: any) => NightwatchAPI;
property toContain
toContain: (value: string) => NightwatchAPI;
property toEndWith
toEndWith: (value: string) => NightwatchAPI;
property toEqual
toEqual: (value: any) => NightwatchAPI;
property toMatch
toMatch: (regexp: RegExp) => NightwatchAPI;
interface ExpectCookie
interface ExpectCookie extends ExpectAssertions<ExpectCookie> {}
interface ExpectElement
interface ExpectElement extends ExpectAssertions<ExpectElement> {}
property active
active: Awaitable<this, NightwatchExpectResult>;
Property that checks if an element is active in the DOM.
property enabled
enabled: Awaitable<this, NightwatchExpectResult>;
Property that checks if an element is currently enabled.
property present
present: Awaitable<this, NightwatchExpectResult>;
Property that checks if an element is present in the DOM.
property selected
selected: Awaitable<this, NightwatchExpectResult>;
Property that checks if an OPTION element, or an INPUT element of type checkbox or radio button is currently selected.
property text
text: Awaitable<this, NightwatchExpectResult>;
Property that retrieves the text contained by an element. Can be chained to check if contains/equals/matches the specified text or regex.
property value
value: Awaitable<this, NightwatchExpectResult>;
Property that retrieves the value (i.e. the value attributed) of an element. Can be chained to check if contains/equals/matches the specified text or regex.
property visible
visible: Awaitable<this, NightwatchExpectResult>;
Property that asserts the visibility of a specified element.
method a
a: (type: string, message?: string) => Awaitable<this, NightwatchExpectResult>;
Checks if the type (i.e. tag name) of a specified element is of an expected value.
method an
an: (type: string, message?: string) => Awaitable<this, NightwatchExpectResult>;
Checks if the type (i.e. tag name) of a specified element is of an expected value.
method attribute
attribute: ( attribute: string, message?: string) => Awaitable<this, NightwatchExpectResult>;
Checks if a given attribute of an element exists and optionally if it has the expected value.
method css
css: ( property: string, message?: string) => Awaitable<this, NightwatchExpectResult>;
Checks a given css property of an element exists and optionally if it has the expected value.
method domProperty
domProperty: ( propertyName: string, message?: string) => Awaitable<this, NightwatchExpectResult>;
Checks if the specified DOM property of a given element is present and has the expected value. For all the available DOM element properties, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element).
method property
property: ( name: string, message?: string) => Awaitable<this, NightwatchExpectResult>;
Checks if a given DOM property of an element has the expected value. For all the available DOM element properties, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element).
interface ExpectElements
interface ExpectElements extends ExpectAssertions<ExpectElements> {}
property count
count: this;
Checks if the number of elements specified by a selector is equal or not to a given value.
interface ExpectEndWith
interface ExpectEndWith<T> {}
call signature
(value: string): Awaitable<T, NightwatchExpectResult>;
interface ExpectEqual
interface ExpectEqual<T> {}
call signature
(value: any): Awaitable<T, NightwatchExpectResult>;
interface ExpectInclude
interface ExpectInclude<T> {}
call signature
(value: string): Awaitable<T, NightwatchExpectResult>;
interface ExpectLanguageChains
interface ExpectLanguageChains<T> {}
property and
and: T;
property at
at: T;
property be
be: T;
property been
been: T;
property deep
deep: T;
Sets the
deep
flag, later to be used by theequal
.
property does
does: T;
property has
has: T;
property have
have: T;
property is
is: T;
property not
not: T;
Negates any of assertions following in the chain.
property of
of: T;
property same
same: T;
property that
that: T;
property to
to: T;
property which
which: T;
property with
with: T;
interface ExpectMatch
interface ExpectMatch<T> {}
call signature
(regexp: RegExp): Awaitable<T, NightwatchExpectResult>;
interface ExpectSection
interface ExpectSection extends ExpectAssertions<ExpectSection>, ExpectElement {}
interface ExpectStartWith
interface ExpectStartWith<T> {}
call signature
(value: string): Awaitable<T, NightwatchExpectResult>;
interface ExpectTitle
interface ExpectTitle extends ExpectAssertions<ExpectTitle> {}
interface ExpectUrl
interface ExpectUrl extends ExpectAssertions<ExpectUrl> {}
interface FirefoxNsCommands
interface FirefoxNsCommands<ReturnType = unknown> {}
method getContext
getContext: () => Awaitable<IfUnknown<ReturnType, this>, FirefoxContext>;
method installAddon
installAddon: ( path: string, temporary?: boolean) => Awaitable<IfUnknown<ReturnType, this>, string>;
method setContext
setContext: ( ctx: FirefoxContext | PromiseLike<FirefoxContext>) => Awaitable<IfUnknown<ReturnType, this>, null>;
method uninstallAddon
uninstallAddon: ( addonId: string | PromiseLike<string>) => Awaitable<IfUnknown<ReturnType, this>, null>;
interface HttpRequestOptions
interface HttpRequestOptions {}
property auth
auth?: { user: string; pass: string;};
property data
data?: unknown;
property host
host?: string;
property method
method: 'POST' | 'GET' | 'DELETE' | 'PUT';
property path
path?: string;
The pathname of the endpoint to call. Ex:
'/session/:sessionId/url'
.Alternatively, url property could be provided with the full URL.
property port
port?: number;
property sessionId
sessionId: string;
For custom-commands, set to
this.api.sessionId
.
property url
url?: string;
The full URL to call. Ex:
http://localhost:4444/session/:sessionId/url
.
property use_ssl
use_ssl?: boolean;
interface JSON_WEB_OBJECT
interface JSON_WEB_OBJECT extends ElementResult {}
property getId
getId: () => string;
interface Level
interface Level {}
interface LogsNsCommands
interface LogsNsCommands<ReturnType = unknown> {}
method captureBrowserConsoleLogs
captureBrowserConsoleLogs: ( onEventCallback: ( event: Pick< Protocol.Runtime.ConsoleAPICalledEvent, 'type' | 'timestamp' | 'args' > ) => void, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Listen to the
console
events (ex.console.log
event) and register callback to process the same.Example 1
describe('capture console events', function() { it('captures and logs console.log event', function() { browser .captureBrowserConsoleLogs((event) => { console.log(event.type, event.timestamp, event.args[0].value); }) .navigateTo('https://www.google.com') .executeScript(function() { console.log('here'); }, []); }); });
See Also
https://nightwatchjs.org/guide/running-tests/capture-console-messages.html
method captureBrowserExceptions
captureBrowserExceptions: ( onExceptionCallback: (event: Protocol.Runtime.ExceptionThrownEvent) => void, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Catch the JavaScript exceptions thrown in the browser.
Example 1
describe('catch browser exceptions', function() { it('captures the js exceptions thrown in the browser', async function() { await browser.captureBrowserExceptions((event) => { console.log('>>> Exception:', event); });
await browser.navigateTo('https://duckduckgo.com/');
const searchBoxElement = await browser.findElement('input[name=q]'); await browser.executeScript(function(_searchBoxElement) { _searchBoxElement.setAttribute('onclick', 'throw new Error("Hello world!")'); }, [searchBoxElement]);
await browser.elementIdClick(searchBoxElement.getId()); }); });
See Also
https://nightwatchjs.org/guide/running-tests/catch-js-exceptions.html
method getSessionLog
getSessionLog: { ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchLogEntry[]> ) => void ): Awaitable<IfUnknown<ReturnType, this>, NightwatchLogEntry[]>; ( typeString: NightwatchLogTypes, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchLogEntry[]> ) => void ): Awaitable<IfUnknown<ReturnType, this>, NightwatchLogEntry[]>;};
Gets a log from Selenium.
Example 1
describe('get log from Selenium', function() { it('get browser log (default)', function(browser) { browser.logs.getSessionLog(function(result) { if (result.status === 0) { const logEntriesArray = result.value; console.log('Log length: ' + logEntriesArray.length); logEntriesArray.forEach(function(log) { console.log('[' + log.level + '] ' + log.timestamp + ' : ' + log.message); }); } }); });
it('get driver log with ES6 async/await', async function(browser) { const driverLogAvailable = await browser.logs.isAvailable('driver'); if (driverLogAvailable) { const logEntriesArray = await browser.logs.getSessionLog('driver'); logEntriesArray.forEach(function(log) { console.log('[' + log.level + '] ' + log.timestamp + ' : ' + log.message); }); } }); });
See Also
https://nightwatchjs.org/api/logs/getSessionLog.html
method getSessionLogTypes
getSessionLogTypes: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchLogTypes[]> ) => void) => Awaitable<IfUnknown<ReturnType, this>, NightwatchLogTypes[]>;
Gets the available log types. More info about log types in WebDriver can be found here: https://github.com/SeleniumHQ/selenium/wiki/Logging
Example 1
describe('get available log types', function() { it('get log types', function(browser) { browser.logs.getSessionLogTypes(function(result) { if (result.status === 0) { const logTypes = result.value; console.log('Log types available:', logTypes); } }); });
it('get log types with ES6 async/await', async function(browser) { const logTypes = await browser.logs.getSessionLogTypes(); console.log('Log types available:', logTypes); }); });
See Also
https://nightwatchjs.org/api/logs/getSessionLogTypes.html
method isSessionLogAvailable
isSessionLogAvailable: { ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void ): Awaitable<IfUnknown<ReturnType, this>, boolean>; ( typeString: NightwatchLogTypes, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void ): Awaitable<IfUnknown<ReturnType, this>, boolean>;};
Utility command to test if the log type is available.
Example 1
describe('test if the log type is available', function() { it('test browser log type', function(browser) { browser.logs.isSessionLogAvailable('browser', function(result) { if (result.status === 0) { const isAvailable = result.value; if (isAvailable) { // do something more in here } } }); });
it('test driver log type with ES6 async/await', async function(browser) { const isAvailable = await browser.logs.isSessionLogAvailable('driver'); if (isAvailable) { // do something more in here } }); });
See Also
https://nightwatchjs.org/api/logs/isSessionLogAvailable.html
interface NamespacedApi
interface NamespacedApi<ReturnType = unknown> {}
property alerts
alerts: AlertsNsCommands<ReturnType>;
property appium
appium: AppiumCommands<ReturnType>;
property assert
assert: Assert<ReturnType>;
property chrome
chrome: ChromeNsCommands<ReturnType>;
property cookies
cookies: CookiesNsCommands<ReturnType>;
property document
document: DocumentNsCommands<ReturnType>;
property expect
expect: Expect;
property firefox
firefox: FirefoxNsCommands<ReturnType>;
property logs
logs: LogsNsCommands<ReturnType>;
property network
network: NetworkNsCommands<ReturnType>;
property verify
verify: Assert<ReturnType>;
property window
window: WindowNsCommands<ReturnType>;
interface NetworkNsCommands
interface NetworkNsCommands<ReturnType = unknown> {}
method captureRequests
captureRequests: ( onRequestCallback: ( requestParams: Protocol.Network.RequestWillBeSentEvent ) => void, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Capture outgoing network calls from the browser.
Example 1
describe('capture network requests', function() { it('captures and logs network requests as they occur', function(this: ExtendDescribeThis<{requestCount: number}>) { this.requestCount = 1; browser .network.captureRequests((requestParams) => { console.log('Request Number:', this.requestCount!++); console.log('Request URL:', requestParams.request.url); console.log('Request method:', requestParams.request.method); console.log('Request headers:', requestParams.request.headers); }) .navigateTo('https://www.google.com'); }); });
See Also
https://nightwatchjs.org/guide/network-requests/capture-network-calls.html
method mockResponse
mockResponse: ( urlToIntercept: string, response?: { status?: Protocol.Fetch.FulfillRequestRequest; headers?: { [name: string]: string }; body?: Protocol.Fetch.FulfillRequestRequest; }, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Intercept the request made on a particular URL and mock the response.
Example 1
describe('mock network response', function() { it('intercepts the request made to Google search and mocks its response', function() { browser .network.mockResponse('https://www.google.com/', { status: 200, headers: { 'Content-Type': 'UTF-8' }, body: 'Hello there!' }) .navigateTo('https://www.google.com/') .pause(2000); }); });
See Also
https://nightwatchjs.org/guide/network-requests/mock-network-response.html
method setConditions
setConditions: ( spec: NetworkConditionsSpec, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Command to set Chrome network emulation settings.
Example 1
describe('set network conditions', function() { it('sets the network conditions',function() { browser .network.setConditions({ offline: false, latency: 3000, download_throughput: 500 * 1024, upload_throughput: 500 * 1024 }); }); });
See Also
https://nightwatchjs.org/api/setNetworkConditions.html
interface Nightwatch
interface Nightwatch {}
property app
app: NightwatchAPI;
property browser
browser: NightwatchAPI;
property by
by: typeof SeleniumBy;
property Capabilities
Capabilities: typeof Capabilities;
property Key
Key: NightwatchKeys;
method cli
cli: (callback: () => void) => void;
Internal method in Nightwatch.
method client
client: ( settings: NightwatchOptions, reporter?: any, argv?: {}, skipInt?: boolean) => this;
Internal method in Nightwatch.
method CliRunner
CliRunner: (argv?: {}) => this;
Internal method in Nightwatch.
method createClient
createClient: ({ headless, silent, output, useAsync, env, timeout, parallel, reporter, browserName, globals, devtools, debug, enable_global_apis, config, test_settings,}?: CreateClientParams) => NightwatchProgrammaticAPIClient;
Creates a new Nightwatch client that can be used to create WebDriver sessions.
Example 1
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 Also
https://nightwatchjs.org/api/programmatic/#programmatic-api
method initClient
initClient: (opts?: {}) => this;
Internal method in Nightwatch.
method runner
runner: (argv?: {}, done?: () => void, settings?: {}) => Promise<void>;
Internal method in Nightwatch.
Deprecated
method runTests
runTests: ( testSource: string | string[], settings?: any, ...args: any[]) => Promise<void>;
Internal method in Nightwatch.
interface NightwatchAPI
interface NightwatchAPI extends SharedCommands, WebDriverProtocol, NightwatchCustomCommands, NightwatchApiCommands, NamespacedApi<NightwatchAPI> {}
property baseUrl
baseUrl: string;
property currentTest
currentTest: NightwatchTestSuite;
property driver
driver: WebDriver;
https://www.selenium.dev/selenium/docs/api/javascript/WebDriver.html
property ensure
ensure: Ensure;
property globals
globals: NightwatchGlobals;
property Keys
Keys: NightwatchKeys;
property launch_url
launch_url: string;
property launchUrl
launchUrl: string;
property options
options: NightwatchTestOptions;
property page
page: NightwatchPage & NightwatchCustomPageObjects;
property sessionId
sessionId: string;
SessionId of the session used by the Nightwatch api.
method actions
actions: (options?: { async?: boolean; bridge?: boolean }) => Actions;
method setSessionId
setSessionId: (sessionId: string) => this;
Override the sessionId used by Nightwatch client with another session id.
interface NightwatchApiCommands
interface NightwatchApiCommands {}
property browserName
readonly browserName: string;
property platformName
readonly platformName: string;
property WEBDRIVER_ELEMENT_ID
readonly WEBDRIVER_ELEMENT_ID: string;
method isAndroid
isAndroid: () => boolean;
method isAppiumClient
isAppiumClient: () => boolean;
Whether or not Nightwatch is being used to connect to an Appium server.
method isChrome
isChrome: () => boolean;
method isEdge
isEdge: () => boolean;
method isFirefox
isFirefox: () => boolean;
method isInternetExplorer
isInternetExplorer: () => boolean;
method isIOS
isIOS: () => boolean;
method isMobile
isMobile: () => boolean;
method isOpera
isOpera: () => boolean;
method isSafari
isSafari: () => boolean;
interface NightwatchAssertion
interface NightwatchAssertion<T> {}
Example 1
import {ScopedSelector, NightwatchAssertion} from 'nightwatch';
export const assertion = function ElementHasCount(this: NightwatchAssertion, selector: ScopedSelector, count: number) { this.message =
Testing if element <${selector}> has count: ${count}
;this.expected = count;
this.value = (result) => { return result.value; }
this.evaluate = (value) => { return value === count; }
this.command = async (callback) => { const elementsCount = await this.api.element.findAll(selector).count(); callback({value: elementsCount}); } }
See Also
https://nightwatchjs.org/guide/extending-nightwatch/adding-custom-assertions.html
property api
readonly api: NightwatchAPI;
Nightwatch API
property client
readonly client: NightwatchClientObject;
Nightwatch Client
property negate
readonly negate: boolean;
Use this.negate to determine if ".not" is in use
property options
options?: { elementSelector: boolean;};
If the custom commands operates with DOM elements, this options should be set
method actual
actual: (passed: boolean) => string;
When defined, this method is called by the assertion runner with the command result to determine the actual state of the assertion in the event of a failure
method command
command: ( this: Pick<NightwatchAssertion<T>, 'client' | 'api' | 'negate'>, callback: (result: NightwatchAssertionSuccessfulResult<T>) => void) => unknown;
The command which is to be executed by the assertion runner; Nightwatch api is available as this.api
method evaluate
evaluate: (value: T) => boolean;
Given the value, the condition used to evaluate if the assertion is passed
Remarks
This option can also override the pass method. this.pass or this.evaluate must be specified! *
method failure
failure: (result: NightwatchAssertionFailedResult<T>) => boolean;
When defined, this method is called by the assertion runner with the command result, to determine if the value can be retrieved successfully from the result object
method pass
pass: (value: T) => unknown;
The method which performs the actual assertion. It is called with the result of the value method as the argument.
This option can also override the evaluate method. this.pass or this.evaluate must be specified.
method value
value: (result: NightwatchAssertionSuccessfulResult<T>) => T;
Called with the result object of the command to retrieve the value which is to be evaluated
interface NightwatchAssertionFailedResult
interface NightwatchAssertionFailedResult<T> {}
interface NightwatchAssertions
interface NightwatchAssertions<ReturnType> extends NightwatchCommonAssertions<ReturnType>, NightwatchCustomAssertions<ReturnType> {}
property not
not: Omit<NightwatchAssertions<ReturnType>, 'not'>;
Negates any of assertions following in the chain.
interface NightwatchAssertionsError
interface NightwatchAssertionsError {}
interface NightwatchAssertionsResult
interface NightwatchAssertionsResult<T> {}
interface NightwatchAssertionSuccessfulResult
interface NightwatchAssertionSuccessfulResult<T> {}
property value
value?: T;
interface NightwatchBrowser
interface NightwatchBrowser extends NightwatchAPI, NightwatchComponentTestingCommands, NightwatchCustomCommands {}
Deprecated
Use
NightwatchAPI
instead.
interface NightwatchCallbackResultError
interface NightwatchCallbackResultError {}
interface NightwatchClient
interface NightwatchClient extends NightwatchClientObject {}
property argv
argv: { [key: string]: any };
property client
client: NightwatchClientObject;
property configLocateStrategy
configLocateStrategy: 'css selector' | 'xpath';
property unitTestingMode
unitTestingMode: boolean;
property usingCucumber
usingCucumber: boolean;
interface NightwatchClientObject
interface NightwatchClientObject {}
property api
api: NightwatchAPI;
property locateStrategy
locateStrategy: LocateStrategy;
property options
options: NightwatchOptions;
property sessionId
sessionId: string | null;
property settings
settings: NightwatchOptions;
interface NightwatchCommonAssertions
interface NightwatchCommonAssertions<ReturnType> {}
property NightwatchAssertionsError
NightwatchAssertionsError: NightwatchAssertionsError;
method attributeContains
attributeContains: ( selector: Definition, attribute: string, expected: string, message?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Checks if the given attribute of an element contains the expected value.
this.demoTest = function (browser) {browser.assert.attributeContains('#someElement', 'href', 'google.com');};
method attributeEquals
attributeEquals: ( selector: Definition, attribute: string, expected: string, message?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Checks if the given attribute of an element has the expected value.
this.demoTest = function (browser) {browser.assert.attributeEquals('body', 'data-attr', 'some value');};
method attributeMatches
attributeMatches: ( selector: Definition, attribute: string, regex: string | RegExp, msg?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Check if an element's attribute value matches a regular expression.
Example 1
this.demoTest = function (browser) {browser.assert.attributeMatches('body', 'data-attr', '(value)');};
method containsText
containsText: ( selector: Definition, expectedText: string, message?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Checks if the given element contains the specified text.
this.demoTest = function (browser) {browser.assert.containsText('#main', 'The Night Watch');};Deprecated
In favour of
assert.textContains()
.
method cssClassNotPresent
cssClassNotPresent: ( selector: Definition, className: string, msg?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Checks if the given element does not have the specified CSS class.
this.demoTest = function (browser) {browser.assert.cssClassNotPresent('#main', 'container');};Deprecated
In favour of
assert.not.hasClass()
.
method cssClassPresent
cssClassPresent: ( selector: Definition, className: string, message?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Checks if the given element has the specified CSS class.
this.demoTest = function (browser) {browser.assert.cssClassPresent('#main', 'container');};Deprecated
In favour of
assert.hasClass()
.
method cssProperty
cssProperty: ( selector: Definition, cssProperty: string, expected: string, msg?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Checks if the specified css property of a given element has the expected value.
this.demoTest = function (browser) {browser.assert.cssProperty('#main', 'display', 'block');};
method domPropertyContains
domPropertyContains: ( selector: Definition, domProperty: string, expected: string | number, msg?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<any>>;
Checks if the specified DOM property of a given element has the expected value. For all the available DOM element properties, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element). Several properties can be specified (either as an array or command-separated list). Nightwatch will check each one for presence.
method domPropertyEquals
domPropertyEquals: ( selector: Definition, domProperty: string, expected: string | number, msg?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<any>>;
Checks if the specified DOM property of a given element has the expected value. For all the available DOM element properties, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element). If the result value is JSON object or array, a deep equality comparison will be performed.
method domPropertyMatches
domPropertyMatches: ( selector: Definition, domProperty: string, expected: string | RegExp, msg?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<any>>;
Check if specified DOM property value of a given element matches a regex. For all the available DOM element properties, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element).
method elementNotPresent
elementNotPresent: ( selector: Definition, msg?: string) => Awaitable< IfUnknown<ReturnType, this>, NightwatchAssertionsResult<ElementResult[]>>;
Checks if the given element does not exists in the DOM.
Example 1
this.demoTest = function (browser) {browser.assert.elementNotPresent(".should_not_exist");};Deprecated
In favour of
assert.not.elementPresent()
.
method elementPresent
elementPresent: ( selector: ScopedSelector, msg?: string) => Awaitable< IfUnknown<ReturnType, this>, NightwatchAssertionsResult<ElementResult[]>>;
Checks if the given element exists in the DOM.
this.demoTest = function (browser) {browser.assert.elementPresent("#main");};
method elementsCount
elementsCount: ( selector: ScopedSelector, count: number, msg?: string) => Awaitable< IfUnknown<ReturnType, this>, NightwatchAssertionsResult<JSON_WEB_OBJECT[]> & { WebdriverElementId: string; }>;
Checks if the number of elements specified by a selector is equal to a given value.
Example 1
this.demoTest = function (browser) { browser.assert.elementsCount('div', 10); browser.assert.not.elementsCount('div', 10); }
method enabled
enabled: ( selector: Definition, message?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<boolean>>;
Checks if the given element is enabled (as indicated by the 'disabled' attribute).
Example 1
this.demoTest = function (browser) { browser.assert.enabled('.should_be_enabled'); browser.assert.enabled({selector: '.should_be_enabled'}); browser.assert.enabled({selector: '.should_be_enabled', suppressNotFoundErrors: true}); };
method hasAttribute
hasAttribute: ( selector: Definition, expectedAttribute: string, msg?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Checks if the given element contains the specified DOM attribute.
Equivalent of: https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttribute
Example 1
this.demoTest = function (browser) {browser.assert.hasAttribute('#main', 'data-track');};
method hasClass
hasClass: ( selector: Definition, className: string | string[], msg?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Checks if the given element has the specified CSS class.
Example 1
this.demoTest = function (browser) {browser.assert.hasClass('#main', 'container');browser.assert.hasClass('#main', ['visible', 'container']);browser.assert.hasClass('#main', 'visible container');};
method hidden
hidden: ( selector: Definition, msg?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<boolean>>;
Checks if the given element is not visible on the page.
Example 1
this.demoTest = function (browser) {browser.assert.hidden('.should_not_be_visible');};Deprecated
In favour of
assert.not.visible()
.
method selected
selected: ( selector: Definition, message?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<boolean>>;
Checks if the given element is selected.
Example 1
this.demoTest = function (browser) { browser.assert.selected('.should_be_selected'); browser.assert.selected({selector: '.should_be_selected'}); browser.assert.selected({selector: '.should_be_selected', suppressNotFoundErrors: true}); };
method textContains
textContains: ( selector: Definition, expectedText: string, msg?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Checks if the given element contains the specified text.
Example 1
this.demoTest = function (browser) {browser.assert.textContains('#main', 'The Night Watch');};
method textEquals
textEquals: ( selector: Definition, expectedText: string, msg?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Check if an element's inner text equals the expected text.
Example 1
this.demoTest = function (browser) {browser.assert.textEquals('#main', 'The Night Watch');};
method textMatches
textMatches: ( selector: Definition, regex: string | RegExp, msg?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Check if an elements inner text matches a regular expression.
Example 1
this.demoTest = function (browser) {browser.assert.textMatches('#main', '^Nightwatch');};
method title
title: ( expected: string, message?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Checks if the page title equals the given value.
this.demoTest = function (browser) {browser.assert.title("Nightwatch.js");};Deprecated
In favour of
titleEquals()
.
method titleContains
titleContains: ( expected: string, message?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Checks if the page title equals the given value.
this.demoTest = function (browser) {browser.assert.title("Nightwatch.js");};
method titleEquals
titleEquals: ( expected: string, message?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Checks if the page title equals the given value. 2.0
this.demoTest = function (browser) {browser.assert.titleEquals("Nightwatch.js");};
method titleMatches
titleMatches: ( regex: string | RegExp, msg?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Checks if the current title matches a regular expression.
Example 1
this.demoTest = function (browser) {browser.assert.titleMatches('^Nightwatch');};
method urlContains
urlContains: ( expectedText: string, message?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Checks if the current URL contains the given value.
this.demoTest = function (browser) {browser.assert.urlContains('google');};
method urlEquals
urlEquals: ( expected: string, message?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Checks if the current url equals the given value.
this.demoTest = function (browser) {browser.assert.urlEquals('https://www.google.com');};
method urlMatches
urlMatches: ( regex: string | RegExp, msg?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Checks if the current url matches a regular expression.
Example 1
this.demoTest = function (browser) {browser.assert.urlMatches('^https');};
method value
value: ( selector: Definition, expectedText: string, message?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Checks if the given form element's value equals the expected value.
this.demoTest = function (browser) {browser.assert.value("form.login input[type=text]", "username");};Deprecated
In favour of
assert.valueEquals()
.
method valueContains
valueContains: ( selector: Definition, expectedText: string, message?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Checks if the given form element's value contains the expected value.
this.demoTest = function (browser) {browser.assert.valueContains("form.login input[type=text]", "username");};
method valueEquals
valueEquals: ( selector: Definition, expected: string, msg?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<string>>;
Checks if the given form element's value equals the expected value.
The existing .assert.value() command.
Example 1
this.demoTest = function (browser) {browser.assert.valueEquals("form.login input[type=text]", "username");};
method visible
visible: ( selector: Definition, message?: string) => Awaitable<IfUnknown<ReturnType, this>, NightwatchAssertionsResult<boolean>>;
Checks if the given element is visible on the page.
this.demoTest = function (browser) {browser.assert.visible(".should_be_visible");};
interface NightwatchComponentTestingCommands
interface NightwatchComponentTestingCommands {}
Deprecated
Please use the types exported by individual plugins.
method importScript
importScript: ( scriptPath: string, options: { scriptType: string; componentType: string }, callback: () => void) => this;
Deprecated
Please use the types exported by individual plugins.
method launchComponentRenderer
launchComponentRenderer: () => this;
Deprecated
Please use the types exported by individual plugins.
method mountComponent
mountComponent: ( componentPath: string, props?: string | (() => void), callback?: () => void) => Element;
Deprecated
Please use the types exported by individual plugins.
method mountReactComponent
mountReactComponent: ( componentPath: string, props?: string | (() => void), callback?: () => void) => Element;
Deprecated
Please use the types exported by individual plugins.
method mountVueComponent
mountVueComponent: ( componentPath: string, options?: any, callback?: () => void) => Element;
Deprecated
Please use the types exported by individual plugins.
interface NightwatchCustomAssertions
interface NightwatchCustomAssertions<ReturnType> {}
property text
text: (selector: string, expectedText: string, msg?: string) => NightwatchAPI;
interface NightwatchCustomCommands
interface NightwatchCustomCommands {}
method localStorageValue
localStorageValue: ( key: string, callback?: (value: string | null) => void) => this;
interface NightwatchCustomCommands
interface NightwatchCustomCommands {}
method consoleLog
consoleLog: (message: string, ...args: any[]) => this;
interface NightwatchCustomCommandsModel
interface NightwatchCustomCommandsModel {}
property command
command: (...args: any[]) => unknown | Promise<unknown>;
Define a custom command
Example 1
class LogMessage implements NightwatchCustomCommandsModel { command() {
return Promise.resolve(); } }
See Also
https://nightwatchjs.org/guide/extending-nightwatch/adding-custom-commands.html#define-a-custom-command
interface NightwatchCustomPageObjects
interface NightwatchCustomPageObjects {}
interface NightwatchCustomPageObjects
interface NightwatchCustomPageObjects {}
interface NightwatchCustomPageObjects
interface NightwatchCustomPageObjects {}
method FileUpload
FileUpload: () => FileUploadPage;
interface NightwatchDesiredCapabilities
interface NightwatchDesiredCapabilities {}
property 'goog:chromeOptions'
'goog:chromeOptions'?: ChromeOptions;
List all the Chrome-specific desired capabilities.
property 'goog:loggingPrefs'
'goog:loggingPrefs'?: { browser?: string | undefined; driver?: string | undefined; server?: string | undefined;};
A JSON object describing the logging level of different components in the browser, the driver, or any intermediary WebDriver servers. Available values for most loggers are "OFF", "SEVERE", "WARNING", "INFO", "CONFIG", "FINE", "FINER", "FINEST", "ALL". This produces a JSON object looking something like: {"loggingPrefs": {"driver": "INFO", "server": "OFF", "browser": "FINE"}}.
property acceptInsecureCerts
acceptInsecureCerts?: boolean;
Indicates whether untrusted and self-signed TLS certificates are implicitly trusted on navigation for the duration of the session.
property acceptSslCerts
acceptSslCerts?: boolean | undefined;
Whether the session should accept all SSL certs by default.
property applicationCacheEnabled
applicationCacheEnabled?: boolean | undefined;
Whether the session can interact with the application cache.
property browserConnectionEnabled
browserConnectionEnabled?: boolean | undefined;
Whether the session can query for the browser's connectivity and disable it if desired.
property browserName
browserName?: string | null;
The name of the browser being used; examples: {chrome|firefox|safari|edge|internet explorer|opera|brave|null}.
property browserVersion
browserVersion?: string;
The browser version, or the empty string if unknown.
property chromeOptions
chromeOptions?: ChromeOptions;
List all the Chrome-specific desired capabilities.
Deprecated
In favour of
goog:chromeOptions
.
property cssSelectorsEnabled
cssSelectorsEnabled?: boolean | undefined;
Whether the session supports CSS selectors when searching for elements.
property databaseEnabled
databaseEnabled?: boolean | undefined;
Whether the session can interact with database storage.
property elementScrollBehaviour
elementScrollBehaviour?: number | undefined;
Allows the user to specify whether elements are scrolled into the viewport for interaction to align with the top (0) or bottom (1) of the viewport. The default value is to align with the top of the viewport. Supported in IE and Firefox (since 2.36)
property handlesAlerts
handlesAlerts?: boolean | undefined;
Whether the session can interact with modal popups, such as window.alert and window.confirm.
property javascriptEnabled
javascriptEnabled?: boolean | undefined;
Whether the session supports executing user supplied JavaScript in the context of the current page (only on HTMLUnitDriver).
property locationContextEnabled
locationContextEnabled?: boolean | undefined;
Whether the session can set and query the browser's location context.
property nativeEvents
nativeEvents?: boolean | undefined;
Whether the session is capable of generating native events when simulating user input.
property platformName
platformName?: string;
A key specifying which platform the browser should be running on. This value should be one of {WINDOWS|XP|VISTA|MAC|LINUX|UNIX|ANDROID|IOS}. When requesting a new session, the client may specify ANY to indicate any available platform may be used. For more information see [GridPlatforms (https://code.google.com/p/selenium/wiki/GridPlatforms)]
property rotatable
rotatable?: boolean | undefined;
Whether the session can rotate the current page's current layout between portrait and landscape orientations (only applies to mobile platforms).
property takesScreenShot
takesScreenShot?: boolean | undefined;
Whether the session supports taking screenshots of the current page.
property unexpectedAlertBehaviour
unexpectedAlertBehaviour?: string | undefined;
What the browser should do with an unhandled alert before throwing out the UnhandledAlertException. Possible values are "accept", "dismiss" and "ignore"
property webStorageEnabled
webStorageEnabled?: boolean | undefined;
Whether the session supports interactions with storage objects (http://www.w3.org/TR/2009/WD-webstorage-20091029/).
index signature
[key: `${string}:${string}`]: unknown;
interface NightwatchElement
interface NightwatchElement extends WebElement {}
interface NightwatchEnsureResult
interface NightwatchEnsureResult {}
interface NightwatchExpectResult
interface NightwatchExpectResult {}
interface NightwatchGlobals
interface NightwatchGlobals extends NightwatchInternalGlobals {}
See Also
https://nightwatchjs.org/guide/concepts/test-globals.html#external-test-globals
index signature
[key: string]: any;
Custom Globals properties
Example 1
myGlobalVar: "some value"
interface NightwatchInternalGlobals
interface NightwatchInternalGlobals {}
property abortOnAssertionFailure
abortOnAssertionFailure?: boolean;
This controls whether to abort the test execution when an assertion failed and skip the rest it's being used in waitFor commands and expect assertions
true
Example 1
abortOnAssertionFailure: true
property abortOnElementLocateError
abortOnElementLocateError?: boolean;
Since 1.4.0 – this controls whether to abort the test execution when an element cannot be located; an error is logged in all cases, but this also enables skipping the rest of the testcase; it's being used in element commands such as .click() or .getText()
false
Example 1
abortOnElementLocateError: false
property asyncHookTimeout
asyncHookTimeout?: number;
Controls the timeout value for async hooks. Expects the done() callback to be invoked within this time or an error is thrown
10000
Example 1
asyncHookTimeout: 10000
property customReporterCallbackTimeout
customReporterCallbackTimeout?: number;
Controls the timeout value for when executing the global async reporter. Expects the done() callback to be invoked within this time or an error is thrown
20000
Example 1
customReporterCallbackTimeout: 20000
property retryAssertionTimeout
retryAssertionTimeout?: number;
Automatically retrying failed assertions - You can tell Nightwatch to automatically retry failed assertions until a given timeout is reached, before the test runner gives up and fails the test.
5000
Example 1
retryAssertionTimeout: 5000
property reuseBrowserSession
reuseBrowserSession?: boolean;
Use the same browser session to run the individual test suites
false
Example 1
reuseBrowserSession: false
property suppressWarningsOnMultipleElementsReturned
suppressWarningsOnMultipleElementsReturned?: boolean;
By default a warning is printed if multiple elements are found using the given locate strategy and selector; set this to true to suppress those warnings
false
Example 1
suppressWarningsOnMultipleElementsReturned: false
property throwOnMultipleElementsReturned
throwOnMultipleElementsReturned?: boolean;
This will cause waitFor commands on elements to throw an error if multiple elements are found using the given locate strategy and selector
false
Example 1
throwOnMultipleElementsReturned: false
property unitTestsTimeout
unitTestsTimeout?: number;
Controls the timeout value for when running async unit tests. Expects the done() callback to be invoked within this time or an error is thrown
2000
Example 1
unitTestsTimeout: 2000
property waitForConditionPollInterval
waitForConditionPollInterval?: number;
This will overwrite the default polling interval (currently 500ms) for waitFor commands and expect assertions that use retry
500
Example 1
waitForConditionPollInterval: 500
property waitForConditionTimeout
waitForConditionTimeout?: number;
Default timeout value in milliseconds for waitFor commands and implicit waitFor value for expect assertions
5000
Example 1
waitForConditionTimeout: 5000
method after
after: (done: (err?: unknown) => void) => void;
External after hook is ran at the very end of the tests run, after closing the Selenium session
Example 1
after(done) { done(); }
method afterEach
afterEach: (browser: NightwatchAPI, done: (err?: unknown) => void) => void;
This will be run after each test suite is finished
Example 1
afterEach(browser, done) { done(); }
method before
before: (done: (err?: unknown) => void) => void;
External before hook is ran at the beginning of the tests run, before creating the Selenium session
Example 1
before(done) { done(); }
method beforeEach
beforeEach: (browser: NightwatchAPI, done: (err?: unknown) => void) => void;
This will be run before each test suite is started
Example 1
beforeEach(browser, done) { done(); }
method onBrowserNavigate
onBrowserNavigate: (browser: NightwatchAPI) => Promise<void>;
Called right after the command .navigateTo() is finished
Example 1
async onBrowserNavigate(browser) { return Promise.resolve(); }
method onBrowserQuit
onBrowserQuit: (browser: NightwatchAPI) => Promise<void>;
Called right before the command .quit() is finished
Example 1
async onBrowserQuit(browser) { return Promise.resolve(); }
method reporter
reporter: (results: unknown, done: (...args: unknown[]) => void) => void;
Custom reporter
Example 1
reporter: function(results, done) { // do something with the results done(results); }
interface NightwatchKeys
interface NightwatchKeys {}
property ADD
ADD: string;
The numpad add (+) key.
property ALT
ALT: string;
The alt key.
property ARROW_DOWN
ARROW_DOWN: string;
The down arrow.
property ARROW_LEFT
ARROW_LEFT: string;
The left arrow.
property ARROW_RIGHT
ARROW_RIGHT: string;
The right arrow.
property ARROW_UP
ARROW_UP: string;
The up arrow.
property BACK_SPACE
BACK_SPACE: string;
The backspace key.
property CANCEL
CANCEL: string;
OS-specific keystroke sequence that performs a cancel action.
property CLEAR
CLEAR: string;
The clear key. This key only appears on full-size Apple keyboards in place of Num Lock key.
property COMMAND
COMMAND: string;
The command (⌘) key.
property CONTROL
CONTROL: string;
The control key.
property DECIMAL
DECIMAL: string;
The numpad decimal (.) key.
property DELETE
DELETE: string;
The delete key.
property DIVIDE
DIVIDE: string;
The numpad divide (/) key.
property DOWN_ARROW
DOWN_ARROW: string;
property END
END: string;
The end key.
property ENTER
ENTER: string;
The enter (numpad) key.
property EQUALS
EQUALS: string;
The equals key.
property ESCAPE
ESCAPE: string;
The escape key.
property F1
F1: string;
The F1 key.
property F10
F10: string;
The F10 key.
property F11
F11: string;
The F11 key.
property F12
F12: string;
The F12 key.
property F2
F2: string;
The F2 key.
property F3
F3: string;
The F3 key.
property F4
F4: string;
The F4 key.
property F5
F5: string;
The F5 key.
property F6
F6: string;
The F6 key.
property F7
F7: string;
The F7 key.
property F8
F8: string;
The F8 key.
property F9
F9: string;
The F9 key.
property HELP
HELP: string;
The help key. This key only appears on older Apple keyboards in place of the Insert key.
property HOME
HOME: string;
The home key.
property INSERT
INSERT: string;
The insert key.
property LEFT_ARROW
LEFT_ARROW: string;
property META
META: string;
The meta (Windows) key.
property MULTIPLY
MULTIPLY: string;
The numpad multiply (*) key.
property NULL
NULL: string;
Releases all held modifier keys.
property NUMPAD0
NUMPAD0: string;
The numpad zero key.
property NUMPAD1
NUMPAD1: string;
The numpad one key.
property NUMPAD2
NUMPAD2: string;
The numpad two key.
property NUMPAD3
NUMPAD3: string;
The numpad three key.
property NUMPAD4
NUMPAD4: string;
The numpad four key.
property NUMPAD5
NUMPAD5: string;
The numpad five key.
property NUMPAD6
NUMPAD6: string;
The numpad six key.
property NUMPAD7
NUMPAD7: string;
The numpad seven key.
property NUMPAD8
NUMPAD8: string;
The numpad eight key.
property NUMPAD9
NUMPAD9: string;
The numpad nine key.
property PAGEDOWN
PAGEDOWN: string;
The page down key.
property PAGEUP
PAGEUP: string;
The page up key.
property PAUSE
PAUSE: string;
The pause key.
property RETURN
RETURN: string;
The return key.
property RIGHT_ARROW
RIGHT_ARROW: string;
property SEMICOLON
SEMICOLON: string;
The semicolon key.
property SEPARATOR
SEPARATOR: string;
The numpad separator (=) key.
property SHIFT
SHIFT: string;
The shift key.
property SPACE
SPACE: string;
The space bar.
property SUBTRACT
SUBTRACT: string;
The numpad subtract (-) key.
property TAB
TAB: string;
The tab key.
property UP_ARROW
UP_ARROW: string;
interface NightwatchLogEntry
interface NightwatchLogEntry {}
interface NightwatchNodeAssertions
interface NightwatchNodeAssertions<ReturnType> {}
method deepEqual
deepEqual: ( actual: any, expected: any, message?: string | Error) => Awaitable< IfUnknown<ReturnType, this>, NightwatchNodeAssertionsResult | Error>;
method deepStrictEqual
deepStrictEqual: ( actual: any, expected: any, message?: string | Error) => Awaitable< IfUnknown<ReturnType, this>, NightwatchNodeAssertionsResult | Error>;
method doesNotMatch
doesNotMatch: ( value: string, regExp: RegExp, message?: string | Error) => Awaitable< IfUnknown<ReturnType, this>, NightwatchNodeAssertionsResult | Error>;
method doesNotReject
doesNotReject: ( block: (() => Promise<any>) | Promise<any>, message?: string | Error) => Awaitable< IfUnknown<ReturnType, this>, NightwatchNodeAssertionsResult | Error>;
method doesNotThrow
doesNotThrow: ( block: () => any, message?: string | Error) => Awaitable< IfUnknown<ReturnType, this>, NightwatchNodeAssertionsResult | Error>;
method equal
equal: ( actual: any, expected: any, message?: string | Error) => Awaitable< IfUnknown<ReturnType, this>, NightwatchNodeAssertionsResult | Error>;
method fail
fail: { (message?: string | Error): Awaitable< IfUnknown<ReturnType, this>, NightwatchNodeAssertionsResult | Error >; ( actual: any, expected: any, message?: string | Error, operator?: string ): Awaitable< IfUnknown<ReturnType, this>, Error | NightwatchNodeAssertionsResult >;};
method ifError
ifError: ( value: any) => Awaitable< IfUnknown<ReturnType, this>, NightwatchNodeAssertionsResult | Error>;
method match
match: ( value: string, regExp: RegExp, message?: string | Error) => Awaitable< IfUnknown<ReturnType, this>, NightwatchNodeAssertionsResult | Error>;
method notDeepEqual
notDeepEqual: ( actual: any, expected: any, message?: string | Error) => Awaitable< IfUnknown<ReturnType, this>, NightwatchNodeAssertionsResult | Error>;
method notDeepStrictEqual
notDeepStrictEqual: ( actual: any, expected: any, message?: string | Error) => Awaitable< IfUnknown<ReturnType, this>, NightwatchNodeAssertionsResult | Error>;
method notEqual
notEqual: ( actual: any, expected: any, message?: string | Error) => Awaitable< IfUnknown<ReturnType, this>, NightwatchNodeAssertionsResult | Error>;
method notStrictEqual
notStrictEqual: ( actual: any, expected: any, message?: string | Error) => Awaitable< IfUnknown<ReturnType, this>, NightwatchNodeAssertionsResult | Error>;
method ok
ok: ( value: any, message?: string | Error) => Awaitable< IfUnknown<ReturnType, this>, NightwatchNodeAssertionsResult | Error>;
method rejects
rejects: ( block: (() => Promise<any>) | Promise<any>, message?: string | Error) => Awaitable< IfUnknown<ReturnType, this>, NightwatchNodeAssertionsResult | Error>;
method strictEqual
strictEqual: ( actual: any, expected: any, message?: string | Error) => Awaitable< IfUnknown<ReturnType, this>, NightwatchNodeAssertionsResult | Error>;
method throws
throws: ( block: () => any, message?: string | Error) => Awaitable< IfUnknown<ReturnType, this>, NightwatchNodeAssertionsResult | Error>;
interface NightwatchNodeAssertionsResult
interface NightwatchNodeAssertionsResult {}
interface NightwatchOptions
interface NightwatchOptions extends NightwatchTestSettingGeneric {}
property always_async_commands
always_async_commands?: boolean;
Whether or not to consider all commands as being running in async mode.
Setting this to true will result in all commands returning a promise, even when they are used in non-async tests.
property backwards_compatibility_mode
backwards_compatibility_mode?: boolean;
Set this to true to use the v1.x response format for commands in v2.x when using ES6 async/await. Can also be used to retain the older functionality of
browser.element()
in v3.x.false
property custom_assertions_path
custom_assertions_path?: string | string[] | null;
Location(s) where custom assertions will be loaded from.
property custom_commands_path
custom_commands_path?: string | string[] | null;
Location(s) where custom commands will be loaded from.
property default_reporter
default_reporter?: string | string[];
junit
property disable_global_apis
disable_global_apis?: boolean;
Set this to true to disable the global objects such as element(), browser, by(), expect()
property disable_global_expect
disable_global_expect?: boolean;
Disable the globally available expect() api.
property disable_typescript
disable_typescript?: boolean;
Disable support for loading of typescript test files for backwards compatibility with test suites.
property dotenv
dotenv?: any;
configuration settings for the dotenv module - a zero-dependency module that loads environment variables from a .env file into process.env. More details on https://www.npmjs.com/package/dotenv
property element_command_retries
element_command_retries?: number;
Interactive element commands such as "click" or "setValue" can be retried if an error occurred (such as an "element not interactable" error)
property globals_path
globals_path?: string | null;
Location of an external globals module which will be loaded and made available to the test as a property globals on the main client instance. Globals can also be defined/overwritten inside a test_settings environment.
property page_objects_path
page_objects_path?: string | string[] | null;
Location(s) where page object files will be loaded from.
property parallel_mode
parallel_mode?: boolean;
property plugins
plugins?: string[];
An array specifying a list of Nightwatch plugin names that should be used.
Example 1
plugins: ['@nightwatch/react']
property report_command_errors
report_command_errors?: boolean;
Whether or not to report API command errors that don't deal with DOM elements (e.g. cookie). false
property report_network_errors
report_network_errors?: boolean;
Whether or not to report network errors (e.g. ECONNRESET errors) true
property report_prefix
report_prefix?: string;
property test_settings
test_settings: NightwatchTestSettings;
This object contains all the test related options. See below for details.
property trace
trace?: { enabled: boolean; path?: string; filename_format?: (failureData: { testSuite: string; testCase: string; isError: boolean; dateObject: Date; }) => string;};
Settings related to tracing [DOM History](https://nightwatchjs.org/guide/reporters/dom-history.html#enable-dom-history).
property tsconfig_path
tsconfig_path?: string;
Location of the tsconfig file to be used by Nightwatch for running tests written in TS. 'nightwatch/tsconfig.json'
property usage_analytics
usage_analytics?: { enabled: boolean; /** * @default './logs/analytics' */ log_path?: string; client_id?: string;};
Settings for anonymous usage metrics collection.
interface NightwatchPosition
interface NightwatchPosition extends WindowPosition {}
interface NightwatchProgrammaticAPIClient
interface NightwatchProgrammaticAPIClient {}
property nightwatch_client
nightwatch_client: NightwatchClient;
property settings
settings: NightwatchOptions;
method launchBrowser
launchBrowser: () => Promise<NightwatchAPI>;
Create a new browser session.
Returns [NightwatchAPI](https://nightwatchjs.org/api/) object.
Example 1
const browser = await client.launchBrowser();
method updateCapabilities
updateCapabilities: (value: {} | (() => {})) => void;
Update the initially specified capabilities.
Example 1
client.updateCapabilities({ testCapability: 'one, two, three' });
interface NightwatchScreenshotOptions
interface NightwatchScreenshotOptions {}
property enabled
enabled: boolean;
property filename_format
filename_format?: (failureData: { testSuite: string; testCase: string; isError: boolean; dateObject: Date;}) => string;
property on_error
on_error?: boolean;
property on_failure
on_failure?: boolean;
property path
path?: string;
interface NightwatchSeleniumOptions
interface NightwatchSeleniumOptions {}
property check_process_delay
check_process_delay?: number;
Time to wait (in ms) before starting to check the Selenium server is up and running 500
property cli_args
cli_args?: {};
List of cli arguments to be passed to the Selenium process. Here you can set various options for browser drivers, such as:
webdriver.firefox.profile
: Selenium will be default create a new Firefox profile for each session. If you wish to use an existing Firefox profile you can specify its name here. Complete list of Firefox Driver arguments available https://code.google.com/p/selenium/wiki/FirefoxDriver.webdriver.chrome.driver
: Nightwatch can run the tests using Chrome browser also. To enable this you have to download the ChromeDriver binary (http://chromedriver.storage.googleapis.com/index.html) and specify it's location here. Also don't forget to specify chrome as the browser name in the desiredCapabilities object. More information can be found on the ChromeDriver website (https://sites.google.com/a/chromium.org/chromedriver/).webdriver.ie.driver
: Nightwatch has support for Internet Explorer also. To enable this you have to download the IE Driver binary (https://code.google.com/p/selenium/wiki/InternetExplorerDriver) and specify it's location here. Also don't forget to specify "internet explorer" as the browser name in the desiredCapabilities object.
property command
command?: string;
Required when using Selenium 4. Set this to 'standalone'.
property host
host?: string;
The IP address Selenium will listen on and/or Nightwatch will attempt to connect to.
property log_path
log_path?: string | boolean;
The location where the selenium Selenium
output.log
file will be placed. Defaults to current directory.To disable Selenium logging, set this to
false
.
property max_status_poll_tries
max_status_poll_tries?: number;
Maximum number of ping status check attempts before returning a timeout error. 15
property port
port?: number;
The port number Selenium will listen on and/or Nightwatch will attempt to connect to.
property server_path
server_path?: string | null;
The location of the selenium jar file. Leave empty if @nightwatch/selenium-server is installed.
Example 1
'lib/selenium-server-standalone-2.43.0.jar'
property start_process
start_process?: boolean;
Whether or not to manage the selenium process automatically. false
property start_session
start_session?: boolean;
Whether or not to automatically start the Selenium session.
property status_poll_interval
status_poll_interval?: number;
Interval (in ms) to use between status ping checks when checking if the Selenium server is up and running. 200
property use_appium
use_appium?: boolean;
Set this to true when using Nightwatch to manage and/or connect to an Appium server.
interface NightwatchServerStatusResult
interface NightwatchServerStatusResult {}
interface NightwatchSize
interface NightwatchSize extends WindowSize {}
interface NightwatchTestFunctions
interface NightwatchTestFunctions {}
property '@disabled'
'@disabled'?: boolean;
property '@tags'
'@tags'?: string | string[];
property after
after?: NightwatchTestHook;
property afterEach
afterEach?: NightwatchTestHook;
property before
before?: NightwatchTestHook;
property beforeEach
beforeEach?: NightwatchTestHook;
index signature
[key: string]: any;
interface NightwatchTestOptions
interface NightwatchTestOptions extends NightwatchTestSettingGeneric {}
property accessKey
accessKey?: string;
This field will be used together with username to compute the Authorization header.
property screenshotsPath
screenshotsPath: string;
Path where screenshots captured during test failure or error will be saved.
property username
username?: string;
In case the selenium server requires credentials this username will be used to compute the Authorization header.
interface NightwatchTestRunner
interface NightwatchTestRunner {}
interface NightwatchTestSettingGeneric
interface NightwatchTestSettingGeneric {}
property base_url
base_url?: string;
A url which can be used later in the tests as the main url to load.
Can be set to different values in different test environments.
baseUrl
,base_url
,launchUrl
,launch_url
in order of precedence.
property baseUrl
baseUrl?: string;
A url which can be used later in the tests as the main url to load.
Can be set to different values in different test environments.
baseUrl
,base_url
,launchUrl
,launch_url
in order of precedence.
property desiredCapabilities
desiredCapabilities?: NightwatchDesiredCapabilities;
An object which will be passed to the Selenium WebDriver when a new session will be created. You can specify browser name for instance along with other capabilities. Example: "desiredCapabilities" : { "browserName" : "firefox", "acceptSslCerts" : true } You can view the complete list of capabilities https://code.google.com/p/selenium/wiki/DesiredCapabilities.
property detailed_output
detailed_output?: boolean;
By default detailed assertion output is displayed while the test is running.
Set this to false if you'd like to only see the test case name displayed and pass/fail status.
Detailed output is disabled by default when running tests in parallel.
property disable_colors
disable_colors?: boolean;
Use to disable colored output in the terminal.
property disable_error_log
disable_error_log?: boolean;
Set this to true if you'd like to not display errors during the execution of the test (they are shown at the end always).
false
property disable_output_boxes
disable_output_boxes?: boolean;
Set this to true if you'd like to disable bounding boxes on terminal output. Useful when running in some CI environments.
property enable_fail_fast
enable_fail_fast?: boolean;
Enable aborting the test run execution when the first test failure occurs; the remaining test suites will be skipped. false
property end_session_on_fail
end_session_on_fail?: boolean;
End the session automatically when the test is being terminated, usually after a failed assertion. true
property exclude
exclude?: string[] | null;
An array of folders or file patterns to be skipped (relative to the main source folder).
Example 1
"exclude" : ["excluded-folder"] or: "exclude" : ["test-folder/*-smoke.js"]
property filter
filter?: string | null;
Folder or file pattern to be used when loading the tests. Files that don't match this pattern will be ignored.
Example 1
"filter": "tests/*-smoke.js"
property globals
globals?: NightwatchGlobals;
An object which will be made available within the test and can be overwritten per environment.
Example 1
"globals": {"myGlobal": "some_global"}
property launch_url
launch_url?: string;
A url which can be used later in the tests as the main url to load.
Can be set to different values in different test environments.
baseUrl
,base_url
,launchUrl
,launch_url
in order of precedence.
property launchUrl
launchUrl?: string;
A url which can be used later in the tests as the main url to load.
Can be set to different values in different test environments.
baseUrl
,base_url
,launchUrl
,launch_url
in order of precedence.
property live_output
live_output?: boolean;
Used when running tests in parallel to determine if the output should be collected and displayed at the end.
false
property log_screenshot_data
log_screenshot_data?: boolean;
Whether or not to show the Base64 image data in the (verbose) log when taking screenshots.
false
property output
output?: boolean;
Used to disable terminal output completely.
true
property output_folder
output_folder?: string;
The location where the JUnit XML and HTML report files will be saved. Set this to false if you want to disable XML/HTML reporting.
'tests_output'
property output_timestamp
output_timestamp?: boolean;
Set this to true if you'd like to see timestamps next to the logging output.
property parallel_process_delay
parallel_process_delay?: number;
Used when running in parallel to specify the delay (in milliseconds) between starting the child processes. 10
property persist_globals
persist_globals?: boolean;
Set this to
true
if you'd like to persist the same globals object between testsuite runs or have a (deep) copy of it per each testsuite.This can be useful when persisting data between test suites is needed, such as a cookie or session information. false
property reporter_options
reporter_options?: { /** * The location where the JUnit XML and HTML report files will be saved. Set this to false if you want to disable XML/HTML reporting. * * @default 'tests_output' */ output_folder?: string;
/** * The name of the parent folder to save the HTML report in. * * This can be used to retain the HTML reports for all the test runs, by making the `folder_format` dynamic. * * @example * folder_format: () => Date.now().toString() */ folder_format?: string | (() => string) | null;
/** * File name to use while saving the HTML report. * * Can be made dynamic by passing a function. Ex. `filename_format: () => Date.now().toString()` * * @default `index.html` */ filename_format?: string | (() => string) | null;
/** * The location where the minimal JSON report should be saved. * This report is used by Nightwatch for its re-run functionality (re-running failed tests from previous run). * * @default 'tests_output/minimal_report.json' */ minimal_report_file_path?: string;};
Settings for generated reports.
property screenshots
screenshots?: NightwatchScreenshotOptions;
Selenium generates screenshots when command errors occur.
With on_failure set to true, also generates screenshots for failing or erroring tests. These are saved on the disk.
Since v0.7.5 you can disable screenshots for command errors by setting "on_error" to false.
Example 1
"screenshots": { "enabled": true, "on_failure": true, "on_error": false, "path": "" }
property selenium
selenium?: NightwatchSeleniumOptions;
An object containing Selenium Server related configuration options. If Selenium Server is not used, webdriver options should be set instead.
Starting with Nightwatch 1.0, Selenium is only required when testing against a Grid setup or a cloud testing service (such as SauceLabs or BrowserStack).
property selenium_host
selenium_host?: string;
The hostname/IP on which the selenium server is accepting connections.
Deprecated
In favour of
selenium.host
.
property selenium_port
selenium_port?: number;
The port number on which the selenium server is accepting connections.
Deprecated
In favour of
selenium.port
.
property silent
silent?: boolean;
Whether to show the extended HTTP traffic command logs from the WebDriver or Selenium server.
true (do not show the extended command logs)
property skip_testcases_on_fail
skip_testcases_on_fail?: boolean;
Skip the remaining test cases from the current test suite, when one test case fails. true
property skipgroup
skipgroup?: string;
Skip a group of tests (a subfolder); can be a list of comma-separated values (no space).
property skiptags
skiptags?: string;
Skip tests by tag name; can be a list of comma-separated values (no space).
property src_folders
src_folders?: string | string[] | null;
An array of folders (excluding subfolders) where the tests are located.
property start_session
start_session?: boolean;
Whether or not to automatically start the Selenium/WebDriver session. If running unit tests, this should be set to false. true
property sync_test_names
sync_test_names?: boolean;
A name property will be added to the
desiredCapabilities
containing the test suite name when this is enabled. It is useful when using cloud testing services.
property tag_filter
tag_filter?: string | string[];
Tag(s) used/to be used during test execution. Can be a single tag or an array of tags.
property test_runner
test_runner?: string | NightwatchTestRunner;
Specifies which test runner to use when running the tests. Set to 'default' to use built-in nightwatch runner.
Example 1
"test_runner": {"type": "mocha", "options": {"ui": "tdd"}}
'default'
property test_workers
test_workers?: boolean | NightwatchTestWorker;
Whether or not to run individual test files in parallel.
If set to
true
, runs the tests in parallel and determines the number of workers automatically.If set to an object, can specify specify the number of workers as "auto" or a number.
Example 1
"test_workers": {"enabled": true, "workers": "auto"}
false
property timestamp_format
timestamp_format?: string;
Set this to 'iso' if you'd like to see timestamps as ISO strings.
property unit_testing_mode
unit_testing_mode?: boolean;
Controls whether to run tests in unit testing mode, which means the session will not automatically be created.=
property unit_tests_mode
unit_tests_mode?: boolean;
Controls whether to run tests in unit testing mode, which means the session will not automatically be created.
Deprecated
In favour of
unit_testing_mode
.
property use_child_process
use_child_process?: boolean;
Specifies which implementation to use for concurrency, child-process or worker-threads.
property use_ssl
use_ssl?: boolean;
Should be set to true if connecting to a remote (cloud) service via HTTPS. Also don't forget to set port to 443.
Deprecated
In favour of
selenium.ssl
. false
property use_xpath
use_xpath?: boolean;
Use xpath as the default locator strategy. false
property webdriver
webdriver?: WebdriverOptions;
An object containing WebDriver related configuration options.
property window_size
window_size?: { height: number; width: number;};
Sets the initial window size: {height: number, width: number}
interface NightwatchTestSettings
interface NightwatchTestSettings {}
index signature
[key: string]: NightwatchTestSettingGeneric & { /** * Inherit settings from another environment. */ extends?: string;};
interface NightwatchTestSuite
interface NightwatchTestSuite {}
interface NightwatchTestWorker
interface NightwatchTestWorker {}
property enabled
enabled: boolean;
property node_options
node_options?: string | string[];
property workers
workers?: 'auto' | number;
interface NightwatchTypedCallbackResult
interface NightwatchTypedCallbackResult<T> {}
interface PageObjectClientCommands
interface PageObjectClientCommands extends ChromiumClientCommands, Pick< NightwatchAPI, | 'axeInject' | 'axeRun' | 'debug' | 'deleteCookie' | 'deleteCookies' | 'end' | 'getCookie' | 'getCookies' | 'getLog' | 'getLogTypes' | 'getTitle' | 'getWindowPosition' | 'getWindowRect' | 'getWindowSize' | 'init' | 'injectScript' | 'isLogAvailable' | 'maximizeWindow' | 'pageSource' | 'pause' | 'perform' | 'registerBasicAuth' | 'resizeWindow' | 'saveScreenshot' // | 'saveSnapshot' // missing from NightwatchAPI | 'setCookie' | 'setWindowPosition' | 'setWindowRect' | 'setWindowSize' | 'urlHash' | 'useCss' | 'useXpath' // | 'within' // missing from NightwatchAPI > {}
interface PageObjectModel
interface PageObjectModel {}
Page objects provide an additional layer of abstraction for test case creation. Page objects are defined in modules and parsed into factory functions that create page object instances.
Remarks
Use satisfies to preserve types!
Example 1
const homePage = { // Some options } satisfies PageObjectModel;
See Also
https://nightwatchjs.org/api/pageobject/#overview
property commands
commands?: | Partial<Record<string, (...args: any) => unknown>> | Partial<Record<string, (...args: any) => unknown>>[];
A list of objects containing functions to represent methods added to the page object instance. Page-specific commands: https://nightwatchjs.org/guide/using-page-objects/writing-page-specific-commands.html
Example 1
class MyCommands { myFirstMethod() { return 'My First Method'; } }
const homePage = { commands: MyCommands } satisfies PageObjectModel;
property elements
elements?: | Partial<{ [name: string]: string | ElementProperties }> | Partial<{ [name: string]: string | ElementProperties }>[];
An object, or array of objects, of named element definitions to be used as element selectors within element commands called from the page object.
Example 1
const homePage = { elements: [ { contactUs: "#contactUs", searchBar: { selector: 'input[type=text]', }, submitButton: { selector: 'input[name=btnK]', }, }, ] } satisfies PageObjectModel;
property props
props?: Record<string, unknown> | (() => Record<string, unknown>);
An object or a function returning an object representing a container for user variables. Props objects are copied directly into the props property of the page object instance.
Example 1
const homePage = { props: { myVar: "some info" } } satisfies PageObjectModel;
property sections
sections?: { [name: string]: SectionProperties;};
An object of named sections definitions defining the sections within the page object.
Example 1
const homePage = { sections: { menu: { selector: '#gb', elements: { mail: { selector: 'a[href="https://mail.google.com/mail/&ogbl"]' } } } } } satisfies PageObjectModel;
property url
url?: string | ((...args: any) => string);
A url or function returning a url to be used in a url() command when the page's navigate() method is called.
Example 1
const homePage = { url: function() { return this.api.launchUrl; } } satisfies PageObjectModel;
interface PageObjectSection
interface PageObjectSection {}
interface ScopedElement
interface ScopedElement extends Element, PromiseLike<WebElement> {}
property assert
assert: ElementAssertions;
property webElement
webElement: WebElementPromise;
method accessibleName
accessibleName: () => ElementValue<string>;
method ariaRole
ariaRole: () => ElementValue<string>;
method attr
attr: (name: string) => ElementValue<string | null>;
method attribute
attribute: (name: string) => ElementValue<string | null>;
method check
check: () => Promise<WebElement>;
method clear
clear: () => Promise<WebElement>;
method click
click: () => Promise<WebElement>;
method clickAndHold
clickAndHold: () => Promise<WebElement>;
method css
css: (name: string) => ElementValue<string>;
method doubleClick
doubleClick: () => Promise<WebElement>;
method dragAndDrop
dragAndDrop: (destination: DragAndDropDestination) => Promise<WebElement>;
method find
find: (selector: ScopedElementSelector) => ScopedElement;
method findAll
findAll: (selector: ScopedSelector | Promise<ScopedSelector>) => Elements;
method findAllByAltText
findAllByAltText: ( text: string, options?: Omit<ScopedSelectorObject, 'selector'> & { readonly exact?: boolean; }) => Elements;
method findAllByPlaceholderText
findAllByPlaceholderText: ( text: string, options?: Omit<ScopedSelectorObject, 'selector'> & { readonly exact?: boolean; }) => Elements;
method findAllByRole
findAllByRole: { ( role: 'heading', options?: Omit<ScopedSelectorObject, 'selector'> & { readonly level?: number; readonly checked?: boolean; readonly current?: boolean | string; readonly pressed?: boolean; readonly expanded?: boolean; readonly selected?: boolean; } ): Elements; ( role: string, options?: Omit<ScopedSelectorObject, 'selector'> & { readonly current?: string | boolean; readonly checked?: boolean; readonly pressed?: boolean; readonly selected?: boolean; readonly expanded?: boolean; } ): Elements;};
method findAllByText
findAllByText: ( text: string, options?: Omit<ScopedSelectorObject, 'selector'> & { readonly exact?: boolean; }) => Elements;
method findByAltText
findByAltText: ( text: string, options?: Omit<ScopedSelectorObject, 'selector'> & { readonly exact?: boolean; }) => ScopedElement;
method findByLabelText
findByLabelText: ( text: string, options?: Omit<ScopedSelectorObject, 'selector'> & { readonly exact?: boolean; }) => ScopedElement;
method findByPlaceholderText
findByPlaceholderText: ( text: string, options?: Omit<ScopedSelectorObject, 'selector'> & { readonly exact?: boolean; }) => ScopedElement;
method findByRole
findByRole: { ( role: 'heading', options?: Omit<ScopedSelectorObject, 'selector'> & { readonly level?: number; readonly checked?: boolean; readonly current?: boolean | string; readonly pressed?: boolean; readonly expanded?: boolean; readonly selected?: boolean; } ): ScopedElement; ( role: string, options?: Omit<ScopedSelectorObject, 'selector'> & { readonly current?: string | boolean; readonly checked?: boolean; readonly pressed?: boolean; readonly selected?: boolean; readonly expanded?: boolean; } ): ScopedElement;};
method findByText
findByText: ( text: string, options?: Omit<ScopedSelectorObject, 'selector'> & { readonly exact?: boolean; }) => ScopedElement;
method findElement
findElement: (selector: ScopedElementSelector) => ScopedElement;
method findElements
findElements: (selector: ScopedSelector | Promise<ScopedSelector>) => Elements;
method get
get: (selector: ScopedElementSelector) => ScopedElement;
method getAccessibleName
getAccessibleName: () => ElementValue<string>;
method getAll
getAll: (selector: ScopedSelector | Promise<ScopedSelector>) => Elements;
method getAllByRole
getAllByRole: ( role: string, options?: Omit<ScopedSelectorObject, 'selector'> & { readonly current?: boolean | string; readonly checked?: boolean; readonly pressed?: boolean; readonly selected?: boolean; readonly expanded?: boolean; }) => Elements;
method getAriaRole
getAriaRole: () => ElementValue<string>;
method getAttribute
getAttribute: (name: string) => ElementValue<string | null>;
method getComputedLabel
getComputedLabel: () => ElementValue<string>;
method getComputedRole
getComputedRole: () => ElementValue<string>;
method getCssProperty
getCssProperty: (name: string) => ElementValue<string>;
method getCssValue
getCssValue: (name: string) => ElementValue<string>;
method getFirstElementChild
getFirstElementChild: () => ScopedElement;
method getId
getId: () => ElementValue<string>;
method getLastElementChild
getLastElementChild: () => ScopedElement;
method getLocation
getLocation: () => ElementValue<ScopedElementRect>;
method getNextElementSibling
getNextElementSibling: () => ScopedElement;
method getPreviousElementSibling
getPreviousElementSibling: () => ScopedElement;
method getProperty
getProperty: (name: string) => ElementValue<string | null>;
method getRect
getRect: () => ElementValue<ScopedElementRect>;
method getShadowRoot
getShadowRoot: () => Omit<ScopedElement, 'then'> & PromiseLike<ShadowRoot>;
method getSize
getSize: () => ElementValue<ScopedElementRect>;
method getTagName
getTagName: () => ElementValue<string>;
method getText
getText: () => ElementValue<string>;
method getValue
getValue: () => ElementValue<string | null>;
method isActive
isActive: () => ElementValue<boolean>;
method isDisplayed
isDisplayed: () => ElementValue<boolean>;
method isEnabled
isEnabled: () => ElementValue<boolean>;
method isPresent
isPresent: () => ElementValue<boolean>;
method isSelected
isSelected: () => ElementValue<boolean>;
method isVisible
isVisible: () => ElementValue<boolean>;
method moveTo
moveTo: (x?: number, y?: number) => Promise<WebElement>;
method prop
prop: (name: string) => ElementValue<string | null>;
method property
property: (name: string) => ElementValue<string | null>;
method rect
rect: () => ElementValue<ScopedElementRect>;
method rightClick
rightClick: () => Promise<WebElement>;
method sendKeys
sendKeys: <E extends readonly unknown[]>(...keys: E) => Promise<WebElement>;
method setAttribute
setAttribute: (name: string, value: string | null) => Promise<WebElement>;
method setProperty
setProperty: (name: string, value: unknown) => Promise<WebElement>;
method setValue
setValue: <E extends readonly unknown[]>(...keys: E) => Promise<WebElement>;
method submit
submit: () => Promise<WebElement>;
method tagName
tagName: () => ElementValue<string>;
method takeScreenshot
takeScreenshot: () => ElementValue<string>;
method text
text: () => ElementValue<string>;
method uncheck
uncheck: () => Promise<WebElement>;
method update
update: <E extends readonly unknown[]>(...keys: E) => Promise<WebElement>;
method upload
upload: (file: string) => Promise<WebElement>;
method waitUntil
waitUntil: ( signalOrOptions: WaitUntilActions | WaitUntilOptions, waitOptions?: WaitUntilOptions) => Promise<WebElement>;
interface SectionProperties
interface SectionProperties {}
property commands
commands?: | Partial<Record<string, (...args: any) => unknown>> | Partial<Record<string, (...args: any) => unknown>>[];
A list of objects containing functions to represent methods added to the section.
Example 1
sections: { apps: { selector: 'div.gb_pc', commands: [ { clickYoutube() { console.log('Click Youtube') } } ] } }
property elements
elements?: | Partial<{ [name: string]: string | ElementProperties }> | Partial<{ [name: string]: string | ElementProperties }>[];
An object, or array of objects, of named element definitions to be used as element selectors within element commands.
Example 1
sections: { apps: { selector: 'div.gb_pc', elements: { myAccount: { selector: '#gb192' }, googlePlus: { selector: '#gb119' } } } }
property locateStrategy
locateStrategy?: LocateStrategy;
The locate strategy to be used with
selector
when finding the section within the DOM. - css selector - link text - partial link text - tag name - xpathExample 1
'css selector'
property props
props?: Record<string, unknown> | (() => Record<string, unknown>);
An object or a function returning an object representing a container for user variables. Props objects are copied directly into the props property of the page object instance.
Example 1
sections: { apps: { selector: 'div.gb_pc', // object version props: { myVar: "some info" } }, menu: { selector: '#gb', // function version props: function () { return { myOtherVar: "some other info" }; } } }
property sections
sections?: { [name: string]: SectionProperties;};
An object of named sections definitions defining the sections.
Example 1
sections: { menu: { selector: '#gb', sections: { apps: { selector: 'div.gb_pc', elements: { myAccount: { selector: '#gb192' } } } } } }
property selector
selector: string;
The selector string to be used to find the section in the DOM.
Example 1
sections: { apps: { selector: 'div.gb_pc' } }
interface SharedCommands
interface SharedCommands extends ClientCommands, ElementCommands {}
interface TimeoutOptions
interface TimeoutOptions {}
property retry_attempts
retry_attempts: number;
2
property timeout
timeout: number;
90000
interface WebdriverOptions
interface WebdriverOptions {}
property access_key
access_key?: string;
This field will be used together with
username
to compute theAuthorization
header.Like
username
, the value can be also an environment variable:"access_key": "${SAUCE_ACCESS_KEY}"
none
property android_chrome
android_chrome?: false;
Configures the ChromeDriver to launch Chrome on Android via adb.
property check_process_delay
check_process_delay?: number;
Time to wait (in ms) before starting to check the Webdriver server is up and running.
100
property chrome_binary
chrome_binary?: string;
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").
property chrome_log_file
chrome_log_file?: string;
Sets the path to Chrome's log file. This path should exist on the machine that will launch Chrome.
property cli_args
cli_args?: string[] | {};
List of cli arguments to be passed to the Webdriver process. This varies for each Webdriver implementation.
none
property default_path_prefix
default_path_prefix?: string;
Needed sometimes when using a Selenium Server. The prefix to be added to to all requests (e.g.
/wd/hub
).
property edge_binary
edge_binary?: '';
Sets the path to the Edge binary to use. This path should exist on the machine that will launch Edge.
property edge_log_file
edge_log_file?: '';
Sets the path to the Edge binary to use.
property firefox_binary
firefox_binary?: '';
Sets the binary to use. The binary may be specified as the path to a Firefox executable or a desired release Channel. This path should exist on the machine that will launch Firefox.
property firefox_profile
firefox_profile?: '';
Sets the path to an existing profile to use as a template for new browser sessions. This profile will be copied for each new session - changes will not be applied to the profile itself.
property host
host?: string;
Only needed when the Webdriver service is running on a different machine.
property internal_server_error_retry_interval
internal_server_error_retry_interval?: number;
Interval (in ms) to wait for before sending another request to the WebDriver server in case of an Internal Server Error (5xx).
Number of times the retry attempts are made depend on
timeout_options.retryAttempts
webdriver setting.
property keep_alive
keep_alive?: | boolean | { enabled: boolean; keepAliveMsecs: number; };
Enable HTTP Keep-Alive.
If set to true, the keepAlive option is enabled with default settings (
keepAliveMsecs
= 3000).If set to an object, you can specify specify the
keepAliveMsecs
value.Example 1
"keep_alive": {"enabled": true, "keepAliveMsecs": 2000}
property log_file_name
log_file_name?: string;
File name to use when writing the webdriver server logs.
By default, the log file name will be the same as the testsuite file name.
property log_path
log_path?: string | boolean;
The location where the Webdriver service log file output.log file will be placed. Defaults to current directory.
To disable Webdriver logging, set this to false. none
property max_status_poll_tries
max_status_poll_tries?: number;
Maximum number of ping status check attempts when checking if the Webdriver server is up and running before returning a timeout error.
5
property port
port?: number;
The port number on which the Webdriver service will listen and/or on which Nightwatch will attempt to connect.
property process_create_timeout
process_create_timeout?: number;
The entire time (in ms) to wait for the Node.js process to be created and running (default is 2 min), including spawning the child process and checking the status.
120000
property proxy
proxy?: string;
Proxy requests to the Webdriver (or Selenium) service. http, https, socks(v5), socks5, sock4, and pac are accepted. Uses node-proxy-agent.
Example 1
http://user:pass@host:port none
property server_path
server_path?: string | null;
Absolute path to the webdriver binary. Only useful if start_process is enabled. none
property ssl
ssl?: boolean;
Should be set to true if connecting to a remote (cloud) service via HTTPS. Also don't forget to set port to 443.
property start_process
start_process?: boolean;
When this is enabled, the Webdriver server is run in background in a child process and started/stopped automatically.
Nightwatch includes support for managing Chromedriver, Geckodriver (Firefox), Safaridriver, and Selenium Server.
false
property status_poll_interval
status_poll_interval?: number;
Interval (in ms) to use between status ping checks when checking if the Webdriver server is up and running.
100
property timeout_options
timeout_options?: TimeoutOptions;
Requests to the Webdriver service will timeout in
timeout
milliseconds; a retry will happenretry_attempts
number of times.Example 1
{timeout: 15000, retry_attempts: 5}
property use_legacy_jsonwire
use_legacy_jsonwire?: boolean;
Some Webdriver implementations (Safari, Edge) support both the W3C Webdriver API as well as the legacy JSON Wire (Selenium) API.
false
property username
username?: string;
Usually only needed for cloud testing Selenium services. In case the server requires credentials this username will be used to compute the
Authorization
header.The value can be also an environment variable, in which case it will look like this:
"username": "${SAUCE_USERNAME}"
none
interface WebDriverProtocol
interface WebDriverProtocol extends WebDriverProtocolSessions, WebDriverProtocolNavigation, WebDriverProtocolCommandContexts, WebDriverProtocolElements, WebDriverProtocolElementState, WebDriverProtocolElementInteraction, WebDriverProtocolElementLocation, WebDriverProtocolDocumentHandling, WebDriverProtocolCookies, WebDriverProtocolUserActions, WebDriverProtocolUserPrompts, WebDriverProtocolScreenCapture, WebDriverProtocolMobileRelated {}
interface WebDriverProtocolCommandContexts
interface WebDriverProtocolCommandContexts {}
method frame
frame: { ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( frameId: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Change focus to another frame on the page. If the frame id is missing or null, the server should switch to the page's default content.
Example 1
this.demoTest = function (browser) { browser.frame('', function(result) { console.log(result); }); }
See Also
https://nightwatchjs.org/api/frame.html
method frameParent
frameParent: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Change focus to the parent context. If the current context is the top level browsing context, the context remains unchanged.
Example 1
this.demoTest = function (browser) { browser.frameParent(function(result) { console.log(result); }); }
See Also
https://nightwatchjs.org/api/frameParent.html
v0.4.8
method windowHandle
windowHandle: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<this, string>;
Retrieve the current window handle.
Example 1
this.demoTest = function (browser) { browser.windowHandle(function(result) { console.log(result.value); }); }
See Also
https://nightwatchjs.org/api/windowHandle.html
Deprecated
In favour of
.window.getHandle()
.
method windowHandles
windowHandles: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string[]> ) => void) => Awaitable<this, string[]>;
Retrieve the list of all window handles available to the session.
Example 1
this.demoTest = function (browser) { browser.windowHandles(function(result) { // An array of window handles. console.log(result.value); }); }
See Also
https://nightwatchjs.org/api/windowHandles.html
Deprecated
In favour of
.window.getAllHandles()
.
method windowMaximize
windowMaximize: ( handleOrName?: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Increases the window to the maximum available size without going full-screen.
Example 1
this.demoTest = function (browser) { browser.windowMaximize('current', function(result) { console.log(result); }); }
See Also
https://nightwatchjs.org/api/windowMaximize.html
Deprecated
In favour of
.window.maximize()
.
method windowPosition
windowPosition: { ( windowHandle: string, offsetX: number, offsetY: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( windowHandle: string, callback: ( this: NightwatchAPI, result: NightwatchCallbackResult<WindowPosition> ) => void ): Awaitable<this, WindowPosition>;};
Change or get the position of the specified window. If the second argument is a function it will be used as a callback and the call will perform a get request to retrieve the existing window position.
Example 1
this.demoTest = function (browser) {
// Change the position of the specified window. // If the :windowHandle URL parameter is "current", the currently active window will be moved. browser.windowPosition('current', 0, 0, function(result) { console.log(result); });
// Get the position of the specified window. // If the :windowHandle URL parameter is "current", the position of the currently active window will be returned. browser.windowPosition('current', function(result) { console.log(result.value); }); }
See Also
https://nightwatchjs.org/api/windowPosition.html
Deprecated
In favour of
.window.getPosition()
and.window.setPosition()
.
method windowRect
windowRect: { ( options: { width?: number; height?: number; x?: number; y?: number }, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( options: null, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<WindowSizeAndPosition> ) => void ): Awaitable<this, WindowSizeAndPosition>;};
Change or get the [window rect](https://w3c.github.io/webdriver/#dfn-window-rect). This is defined as a dictionary of the
screenX
,screenY
,outerWidth
andouterHeight
attributes of the window.Its JSON representation is the following: -
x
- window's screenX attribute; -y
- window's screenY attribute; -width
- outerWidth attribute; -height
- outerHeight attribute.All attributes are in in CSS pixels. To change the window react, you can either specify
width
andheight
,x
andy
or all properties together.Example 1
module.exports = { 'demo test .windowRect()': function(browser) {
// Change the screenX and screenY attributes of the window rect. browser.windowRect({x: 500, y: 500});
// Change the width and height attributes of the window rect. browser.windowRect({width: 600, height: 300});
// Retrieve the attributes browser.windowRect(function(result) { console.log(result.value); }); },
'windowRect ES6 demo test': async function(browser) { const resultValue = await browser.windowRect(); console.log('result value', resultValue); } }
See Also
https://nightwatchjs.org/api/windowRect.html
Deprecated
In favour of
.window.getRect()
and.window.setRect()
.
method windowSize
windowSize: { ( windowHandle: string, width: number, height: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( windowHandle: string, callback: ( this: NightwatchAPI, result: NightwatchCallbackResult<WindowSizeAndPosition> ) => void ): Awaitable<this, WindowSizeAndPosition>;};
Change or get the size of the specified window. If the second argument is a function it will be used as a callback and the call will perform a get request to retrieve the existing window size.
Example 1
this.demoTest = function (browser) {
// Return the size of the specified window. If the :windowHandle URL parameter is "current", the size of the currently active window will be returned. browser.windowSize('current', function(result) { console.log(result.value); });
// Change the size of the specified window. // If the :windowHandle URL parameter is "current", the currently active window will be resized. browser.windowSize('current', 300, 300, function(result) { console.log(result.value); }); }
See Also
https://nightwatchjs.org/api/windowSize.html
Deprecated
In favour of
.window.getSize()
and.window.setSize()
.
interface WebDriverProtocolCookies
interface WebDriverProtocolCookies {}
method cookie
cookie: { ( method: 'GET' | 'DELETE', callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<Cookie[] | null> ) => void ): Awaitable<this, Cookie[] | null>; ( method: 'POST', cookie: Cookie, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( method: 'DELETE', cookieName: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Retrieve or delete all cookies visible to the current page or set a cookie. Normally this shouldn't be used directly, instead the cookie convenience methods should be used: getCookie, getCookies, setCookie, deleteCookie, deleteCookies.
See Also
getCookies
getCookie
setCookie
deleteCookie
deleteCookies
Deprecated
interface WebDriverProtocolDocumentHandling
interface WebDriverProtocolDocumentHandling {}
method execute
execute: { <ReturnValue>( body: ExecuteScriptFunction<[], ReturnValue> | string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<VoidToNull<ReturnValue>> ) => void ): Awaitable<this, VoidToNull<ReturnValue>>; <ArgType extends any[], ReturnValue>( body: string | ExecuteScriptFunction<ArgType, ReturnValue>, args: ArgType, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<VoidToNull<ReturnValue>> ) => void ): Awaitable<this, VoidToNull<ReturnValue>>;};
Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be synchronous. The script argument defines the script to execute in the form of a function body. The value returned by that function will be returned to the client.
The function will be invoked with the provided args array and the values may be accessed via the arguments object in the order specified.
Under the hood, if the
body
param is a function it is converted to a string with<function>.toString()
. Any references to your current scope are ignored.To ensure cross-browser compatibility, the specified function should not be in ES6 format (i.e.
() => {}
). If the execution of the function fails, the first argument of the callback contains error information.Example 1
this.demoTest = function (browser) { browser.execute(function(imageData: string) { // resize operation return true; }, [imageData], function(result) { // result.value === true }); }
See Also
https://nightwatchjs.org/api/execute.html#apimethod-container
executeScript
method executeAsync
executeAsync: { <ReturnValue>( script: ExecuteAsyncScriptFunction<[], ReturnValue> | string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ReturnValue> ) => void ): Awaitable<this, ReturnValue>; <ArgType extends any[], ReturnValue>( script: string | ExecuteAsyncScriptFunction<ArgType, ReturnValue>, args: ArgType, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ReturnValue> ) => void ): Awaitable<this, ReturnValue>;};
Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be asynchronous.
The function to be injected receives the
done
callback as argument which needs to be called when the asynchronous operation finishes. The value passed to thedone
callback is returned to the client. Additional arguments for the injected function may be passed as a non-empty array which will be passed before thedone
callback.Asynchronous script commands may not span page loads. If an unload event is fired while waiting for the script result, an error will be returned.
Example 1
this.demoTest = function (browser) { browser.executeAsync(function(done: (result: true) => void) { setTimeout(function() { done(true); }, 500); }, function(result) { // result.value === true });
browser.executeAsync(function(arg1: string, arg2: number, done: (result: string) => void) { setTimeout(function() { done(arg1); }, 500); }, [arg1, arg2], function(result) { // result.value === arg1 }); }
See Also
https://nightwatchjs.org/api/executeAsyncScript.html
executeAsyncScript
method executeAsyncScript
executeAsyncScript: { <ReturnValue>( script: ExecuteAsyncScriptFunction<[], ReturnValue> | string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ReturnValue> ) => void ): Awaitable<this, ReturnValue>; <ArgType extends any[], ReturnValue>( script: string | ExecuteAsyncScriptFunction<ArgType, ReturnValue>, args: ArgType, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ReturnValue> ) => void ): Awaitable<this, ReturnValue>;};
Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be asynchronous.
The function to be injected receives the
done
callback as argument which needs to be called when the asynchronous operation finishes. The value passed to thedone
callback is returned to the client. Additional arguments for the injected function may be passed as a non-empty array which will be passed before thedone
callback.Asynchronous script commands may not span page loads. If an unload event is fired while waiting for the script result, an error will be returned.
Example 1
this.demoTest = function (browser) { browser.executeAsyncScript(function(done: (result: true) => void) { setTimeout(function() { done(true); }, 500); }, function(result) { // result.value === true });
browser.executeAsyncScript(function(arg1: string, arg2: number, done: (result: string) => void) { setTimeout(function() { done(arg1); }, 500); }, [arg1, arg2], function(result) { // result.value === arg1 }); }
See Also
https://nightwatchjs.org/api/executeAsyncScript.html
executeAsync
method executeScript
executeScript: { <ReturnValue>( body: ExecuteScriptFunction<[], ReturnValue> | string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<VoidToNull<ReturnValue>> ) => void ): Awaitable<this, VoidToNull<ReturnValue>>; <ArgType extends any[], ReturnValue>( body: string | ExecuteScriptFunction<ArgType, ReturnValue>, args: ArgType, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<VoidToNull<ReturnValue>> ) => void ): Awaitable<this, VoidToNull<ReturnValue>>;};
Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be synchronous. The script argument defines the script to execute in the form of a function body. The value returned by that function will be returned to the client.
The function will be invoked with the provided args array and the values may be accessed via the arguments object in the order specified.
Under the hood, if the
body
param is a function it is converted to a string with<function>.toString()
. Any references to your current scope are ignored.To ensure cross-browser compatibility, the specified function should not be in ES6 format (i.e.
() => {}
). If the execution of the function fails, the first argument of the callback contains error information.Example 1
this.demoTest = function (browser) { browser.executeScript(function(imageData: string) { // resize operation return true; }, [imageData], function(result) { // result.value === true }); }
See Also
https://nightwatchjs.org/api/execute.html#apimethod-container
execute
method source
source: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<this, string>;
Returns a string serialisation of the DOM of the current page.
Example 1
browser.source();
See Also
https://nightwatchjs.org/api/source.html
Deprecated
In favour of
.document.source()
.
interface WebDriverProtocolElementInteraction
interface WebDriverProtocolElementInteraction {}
method elementIdClear
elementIdClear: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Scrolls into view a submittable element excluding buttons or editable element, and then attempts to clear its value, reset the checked state, or text content.
Example 1
browser.elementIdClear(elementId);
See Also
https://nightwatchjs.org/api/elementIdClear.html
method elementIdClick
elementIdClick: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Scrolls into view the element and clicks the in-view center point. If the element is not pointer-interactable, an element not interactable error is returned.
Example 1
browser.elementIdClick(elementId);
See Also
https://nightwatchjs.org/api/elementIdClick.html
method elementIdValue
elementIdValue: { ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>; ( id: string, value: string | string[], callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Scrolls into view the form control element and then sends the provided keys to the element, or returns the current value of the element. In case the element is not keyboard interactable, an element not interactable error is returned.
See Also
https://nightwatchjs.org/api/elementIdValue.html
Deprecated
In favour of .getValue() and .setValue()
method keys
keys: ( keysToSend: string | string[], callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Send a sequence of key strokes to the active element. The sequence is defined in the same format as the
sendKeys
command. An object map with available keys and their respective UTF-8 characters, as defined on [W3C WebDriver draft spec](https://www.w3.org/TR/webdriver/#character-types), is loaded onto the main Nightwatch instance asclient.Keys
.Rather than the
setValue
, the modifiers are not released at the end of the call. The state of the modifier keys is kept between calls, so mouse interactions can be performed while modifier keys are depressed.Since v2.0, this command is deprecated. It is only available on older JSONWire-based drivers. Please use the new [User Actions API](https://nightwatchjs.org/api/useractions/).
Example 1
browser .keys(browser.Keys.CONTROL) // hold down CONTROL key .click('#element') .keys(browser.Keys.NULL) // release all keys
See Also
https://nightwatchjs.org/api/keys.html
Deprecated
Please use the new [User Actions API](https://nightwatchjs.org/api/useractions/) instead.
method submit
submit: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Submit a FORM element. The submit command may also be applied to any element that is a descendant of a FORM element.
Example 1
browser.submit(elementID);
See Also
https://nightwatchjs.org/api/submit.html
interface WebDriverProtocolElementLocation
interface WebDriverProtocolElementLocation {}
method elementIdLocation
elementIdLocation: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchSizeAndPosition> ) => void) => Awaitable<this, NightwatchSizeAndPosition>;
Determine an element's location on the page. The point (0, 0) refers to the upper-left corner of the page.
The element's coordinates are returned as a JSON object with x and y properties.
See Also
https://nightwatchjs.org/api/elementIdLocation.html
Deprecated
In favour of .getElementRect()
method elementIdLocationInView
elementIdLocationInView: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchPosition> ) => void) => Awaitable<this, NightwatchPosition>;
Determine an element's location on the screen once it has been scrolled into view.
See Also
https://nightwatchjs.org/api/elementIdLocationInView.html#apimethod-container
Deprecated
This is JSON Wire Protocol command and is no longer supported.
interface WebDriverProtocolElements
interface WebDriverProtocolElements {}
property element
element: ElementFunction;
Provides access to Nightwatch new element API.
Example 1
module.exports = { 'new element api': function (browser) { // Using element as function. const button1 = browser.element('button.submit-form');
// Using the find method of the element namespace. const button2 = browser.element.find('button.submit-form'); // Searching for the icon element inside the .submit-form button. const icon = button2.find('i');
// Use an object to customise locating behaviour. const main = browser.element({ selector: 'main', locateStrategy: 'css selector' }); },
'new element api async': function (browser) { // button is the WebElement object. const button = await browser.element('button.submit-form'); },
'with backward compatibility': function (browser) { // for backward compatibility browser.element('css selector', 'body'); } }
method elementActive
elementActive: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<this, string>;
Get the element on the page that currently has focus. The element will be returned as a [Web Element](https://www.w3.org/TR/webdriver1/#dfn-web-elements) id.
Example 1
module.exports = { 'demo Test' : function(browser) { browser.elementActive(function(result) { console.log(result.value) }); } }
See Also
https://nightwatchjs.org/api/elementActive.html
method elementIdDoubleClick
elementIdDoubleClick: ( webElementId: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Move to the element and performs a double-click in the middle of the given element if element is given else double-clicks at the current mouse coordinates (set by
.moveTo()
).
method elementIdElement
elementIdElement: ( id: string, using: LocateStrategy, value: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ElementResult | []> ) => void) => Awaitable<this, ElementResult | []>;
Search for an element on the page, starting from the identified element. The located element will be returned as a Web Element JSON object.
This command operates on a protocol level and requires a [Web Element ID](https://www.w3.org/TR/webdriver1/#dfn-web-elements). Read more on [Element retrieval](https://www.w3.org/TR/webdriver1/#element-retrieval) on the W3C WebDriver spec page.
Example 1
module.exports = { 'demo Test' : function(browser) { browser.findElement('.some-element', (result) => { this.elementIdElement(result.value.getId(), 'css selector', '.new-element', function(result) { console.log(result.value); }); }); },
'es6 async demo Test': async function(browser) { const elementObject = await browser.findElement('.some-element'); const result = await browser.elementIdElement(elementId.getId(), 'css selector', '.new-element'); console.log(result); } }
See Also
https://nightwatchjs.org/api/elementIdElement.html
method elementIdElements
elementIdElements: ( id: string, using: LocateStrategy, value: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ElementResult[]> ) => void) => Awaitable<this, ElementResult[]>;
Search for multiple elements on the page, starting from the identified element. The located element will be returned as a web element JSON objects.
Example 1
module.exports = { 'demo Test' : function(browser) { browser.findElement('#main', (result) => { browser.elementIdElements(result.value.getId(), 'css selector', 'ul li', function(result) { console.log(result.value) }); }); },
'es6 async demo Test': async function(browser) { const elementObject = await browser.findElement('#main'); const result = await browser.elementIdElements(elementObject.getId(), 'css selector', 'ul li'); console.log(result); } }
See Also
https://nightwatchjs.org/api/elementIdElements.html
method elementIdEquals
elementIdEquals: ( id: string, otherId: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void) => Awaitable<this, boolean>;
Test if two web element IDs refer to the same DOM element.
This command is __deprecated__ and is only available on the [JSON Wire protocol](https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#sessionsessionidelementidequalsother)
Example 1
module.exports = { 'demo Test' : function(browser) { browser.elementIdEquals('', '', function(result) { console.log(result.value) }); } }
See Also
https://nightwatchjs.org/api/elementIdEquals.html
Deprecated
In favour of WebElement.equals(a, b) from Selenium Webdriver.
method elementIdProperty
elementIdProperty: ( webElementId: string, DOMPropertyName: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<any> ) => void) => Awaitable<this, any>;
Retrieve the value of a specified DOM property for the given element. For all the available DOM element properties, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element).
method elements
elements: ( using: LocateStrategy, value: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ElementResult[]> ) => void) => Awaitable<this, ElementResult[]>;
Search for multiple elements on the page, starting from the document root. The located elements will be returned as web element JSON objects. First argument to be passed is the locator strategy, which is detailed on the [WebDriver docs](https://www.w3.org/TR/webdriver/#locator-strategies).
* The locator strategy can be one of: -
css selector
-link text
-partial link text
-tag name
-xpath
Example 1
module.exports = { 'demo Test' : function(browser) { browser.elements('css selector', 'ul li', function(result) { console.log(result.value) }); },
'es6 async demo Test': async function(browser) { const result = await browser.elements('css selector', 'ul li'); console.log('result value is:', result); },
'page object demo Test': function (browser) { var nightwatch = browser.page.nightwatch(); nightwatch .navigate() .assert.titleContains('Nightwatch.js');
nightwatch.api.elements('@featuresList', function(result) { console.log(result); });
browser.end(); } }
See Also
https://nightwatchjs.org/api/elements.html
interface WebDriverProtocolElementState
interface WebDriverProtocolElementState {}
method elementIdAttribute
elementIdAttribute: ( id: string, attributeName: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string | null> ) => void) => Awaitable<this, string | null>;
Get the value of an element's attribute.
See Also
https://nightwatchjs.org/api/elementIdAttribute.html
method elementIdCssProperty
elementIdCssProperty: ( id: string, cssPropertyName: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<this, string>;
Retrieve the computed value of the given CSS property of the given element.
The CSS property to query should be specified using the CSS property name, not the JavaScript property name (e.g. background-color instead of backgroundColor).
See Also
https://nightwatchjs.org/api/elementIdCssProperty.html
method elementIdDisplayed
elementIdDisplayed: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void) => Awaitable<this, boolean>;
Determine if an element is currently displayed.
See Also
https://nightwatchjs.org/api/elementIdDisplayed.html
method elementIdEnabled
elementIdEnabled: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void) => Awaitable<this, boolean>;
Determine if an element is currently enabled.
See Also
https://nightwatchjs.org/api/elementIdEnabled.html
method elementIdName
elementIdName: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<this, string>;
Retrieve the qualified tag name of the given element.
See Also
https://nightwatchjs.org/api/elementIdName.html
method elementIdSelected
elementIdSelected: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void) => Awaitable<this, boolean>;
Determine if an OPTION element, or an INPUT element of type checkbox or radio button is currently selected.
See Also
https://nightwatchjs.org/api/elementIdSelected.html
method elementIdSize
elementIdSize: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchSizeAndPosition> ) => void) => Awaitable<this, NightwatchSizeAndPosition>;
Determine an element's size in pixels. The size will be returned as a JSON object with width and height properties.
See Also
https://nightwatchjs.org/api/elementIdSize.html
Deprecated
In favour of .getElementRect()
method elementIdText
elementIdText: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<this, string>;
Returns the visible text for the element.
See Also
https://nightwatchjs.org/api/elementIdText.html
interface WebDriverProtocolMobileRelated
interface WebDriverProtocolMobileRelated {}
method contexts
contexts: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string[]> ) => void) => Awaitable<this, string[]>;
Get a list of the available contexts.
Example 1
browser.contexts();
Used by Appium when testing hybrid mobile web apps. More info here: https://github.com/appium/appium/blob/master/docs/en/advanced-concepts/hybrid.md.
method currentContext
currentContext: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string | null> ) => void) => Awaitable<this, string | null>;
Get current context.
Example 1
browser.currentContext();
method getOrientation
getOrientation: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<'LANDSCAPE' | 'PORTRAIT'> ) => void) => Awaitable<this, 'LANDSCAPE' | 'PORTRAIT'>;
Get the current browser orientation.
Example 1
browser.getOrientation()
method setContext
setContext: ( context: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Sets the context.
Example 1
browser.setContext(context);
method setOrientation
setOrientation: ( orientation: 'LANDSCAPE' | 'PORTRAIT', callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<'LANDSCAPE' | 'PORTRAIT'> ) => void) => Awaitable<this, 'LANDSCAPE' | 'PORTRAIT'>;
Sets the browser orientation.
Example 1
browser.setOrientation(orientation)
interface WebDriverProtocolNavigation
interface WebDriverProtocolNavigation {}
method back
back: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Navigate backwards in the browser history, if possible.
See Also
https://nightwatchjs.org/api/back.html
method forward
forward: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Navigate forwards in the browser history, if possible.
See Also
https://nightwatchjs.org/api/forward.html
method refresh
refresh: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Refresh the current page.
See Also
https://nightwatchjs.org/api/refresh.html
method title
title: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<this, string>;
Get the current page title.
Example 1
this.demoTest = function (browser) { browser.title(function(result) { console.log(result.value); }); }
See Also
https://nightwatchjs.org/api/title.html
method url
url: { ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>; ( url: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Retrieve the URL of the current page or navigate to a new URL.
Example 1
module.exports = { 'demo Test' : function(browser) { browser.url(function(result) { // return the current url console.log(result); }); // // navigate to new url: browser.url('{URL}'); // // // navigate to new url: browser.url('{URL}', function(result) { console.log(result); }); } }
See Also
https://nightwatchjs.org/api/url.html
interface WebDriverProtocolScreenCapture
interface WebDriverProtocolScreenCapture {}
method screenshot
screenshot: { ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>; ( log_screenshot_data: boolean, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>;};
Take a screenshot of the current page.
Example 1
browser.screenshot(true);
interface WebDriverProtocolSessions
interface WebDriverProtocolSessions {}
method session
session: { ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<Record<string, any>> ) => void ): Awaitable<this, Record<string, any>>; ( actionOrSessionId: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<Record<string, any>> ) => void ): Awaitable<this, Record<string, any>>; ( action: 'POST' | 'GET' | 'DELETE' | 'get' | 'post' | 'delete', sessionId: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<Record<string, any>> ) => void ): Awaitable<this, Record<string, any>>;};
Get info about, delete or create a new session. Defaults to the current session.
Example 1
this.demoTest = function (browser) { browser.session(function(result) { console.log(result.value); }); // browser.session('delete', function(result) { console.log(result.value); }); // browser.session('delete', '12345-abc', function(result) { console.log(result.value); }); }
See Also
https://nightwatchjs.org/api/session.html#apimethod-container
method sessionLog
sessionLog: ( typeString: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchLogEntry[]> ) => void) => Awaitable<this, NightwatchLogEntry[]>;
Gets the text of the log type specified. To find out the available log types, use
.getLogTypes()
.Returns a [log entry JSON object](https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#log-entry-json-object).
Example 1
this.demoTest = function (browser) { browser.sessionLog('client', function(result) { console.log(result.value); }); }
See Also
https://nightwatchjs.org/api/sessionLog.html
method sessionLogTypes
sessionLogTypes: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchLogTypes[]> ) => void) => Awaitable<this, NightwatchLogTypes[]>;
Gets an array of strings for which log types are available. This methods returns the entire WebDriver response, if you are only interested in the logs array, use
.getLogTypes()
instead.Example 1
this.demoTest = function (browser) { browser.sessionLogTypes(function(result) { console.log(result.value); }); }
See Also
https://nightwatchjs.org/api/sessionLogTypes.html
method sessions
sessions: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<Array<Record<string, any>>> ) => void) => Awaitable<this, Array<Record<string, any>>>;
Returns a list of the currently active sessions.
Example 1
this.demoTest = function (browser) { browser.sessions(function(result) { console.log(result.value); }); }
See Also
https://nightwatchjs.org/api/sessions.html
method status
status: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchServerStatusResult> ) => void) => Awaitable<this, NightwatchServerStatusResult>;
Query the server's current status.
See Also
https://nightwatchjs.org/api/status.html
method timeouts
timeouts: { ( typeOfOperation: 'script' | 'implicit' | 'pageLoad', ms: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<{ script: number; implicit: number; pageLoad: number; }> ) => void ): Awaitable<this, { script: number; implicit: number; pageLoad: number }>;};
Configure the amount of time that a particular type of operation can execute for before they are aborted and a |Timeout| error is returned to the client.
Example 1
this.demoTest = function (browser) { browser.timeouts('script', 10000, function(result) { console.log(result); }); }
See Also
https://nightwatchjs.org/api/timeouts.html
method timeoutsAsyncScript
timeoutsAsyncScript: ( ms: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Set the amount of time, in milliseconds, that asynchronous scripts executed by
.executeAsync
are permitted to run before they are aborted and a |Timeout| error is returned to the client.Example 1
this.demoTest = function (browser) { browser.timeoutsAsyncScript(10000, function(result) { console.log(result); }); }
See Also
https://nightwatchjs.org/api/timeoutsAsyncScript.html
method timeoutsImplicitWait
timeoutsImplicitWait: ( ms: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Set the amount of time the driver should wait when searching for elements. If this command is never sent, the driver will default to an implicit wait of 0ms.
Example 1
this.demoTest = function (browser) { browser.timeoutsImplicitWait(10000, function(result) { console.log(result); }); }
See Also
https://nightwatchjs.org/api/timeoutsImplicitWait.html
interface WebDriverProtocolUserActions
interface WebDriverProtocolUserActions {}
method mouseButtonClick
mouseButtonClick: ( button: 0 | 1 | 2 | 'left' | 'middle' | 'right', callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Click at the current mouse coordinates (set by
.moveTo()
).The button can be (0, 1, 2) or ('left', 'middle', 'right'). It defaults to left mouse button.
See Also
https://nightwatchjs.org/api/mouseButtonClick.html
Deprecated
Please use the new [User Actions API](https://nightwatchjs.org/api/useractions/) instead.
method mouseButtonDown
mouseButtonDown: ( button: 0 | 1 | 2 | 'left' | 'middle' | 'right', callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Click and hold the left mouse button (at the coordinates set by the last
moveTo
command). Note that the next mouse-related command that should follow ismouseButtonUp
. Any other mouse command (such as click or another call to buttondown) will yield undefined behaviour.Can be used for implementing drag-and-drop. The button can be (0, 1, 2) or ('left', 'middle', 'right'). It defaults to left mouse button, and if you don't pass in a button but do pass in a callback, it will handle it correctly.
**Since v2.0, this command is deprecated.** It is only available on older JSONWire-based drivers. Please use the new [User Actions API](/api/useractions/).
See Also
https://nightwatchjs.org/api/mouseButtonDown.html
Deprecated
Please use the new [User Actions API](https://nightwatchjs.org/api/useractions/) instead.
method mouseButtonUp
mouseButtonUp: ( button: 0 | 1 | 2 | 'left' | 'middle' | 'right', callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Releases the mouse button previously held (where the mouse is currently at). Must be called once for every
mouseButtonDown
command issued.Can be used for implementing drag-and-drop. The button can be (0, 1, 2) or ('left', 'middle', 'right'). It defaults to left mouse button, and if you don't pass in a button but do pass in a callback, it will handle it correctly.
**Since v2.0, this command is deprecated.** It is only available on older JSONWire-based drivers. Please use the new [User Actions API](/api/useractions/).
See Also
https://nightwatchjs.org/api/mouseButtonUp.html
Deprecated
Please use the new [User Actions API](https://nightwatchjs.org/api/useractions/) instead.
method moveTo
moveTo: { ( elementId: string | null, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( xoffset: number, yoffset: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( elementId: string, xoffset: number, yoffset: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Move the mouse by an offset of the specified [Web Element ID](https://www.w3.org/TR/webdriver1/#dfn-web-elements) or relative to the current mouse cursor, if no element is specified. If an element is provided but no offset, the mouse will be moved to the center of the element.
If an element is provided but no offset, the mouse will be moved to the center of the element. If the element is not visible, it will be scrolled into view.
Example 1
this.demoTest = function (browser) { browser.moveTo(null, 110, 100); };
See Also
https://nightwatchjs.org/api/moveTo.html#apimethod-container
method releaseMouseButton
releaseMouseButton: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Release the depressed left mouse button at the current mouse coordinates (set by
.moveTo()
).See Also
https://nightwatchjs.org/api/releaseMouseButton.html#apimethod-container
interface WebDriverProtocolUserPrompts
interface WebDriverProtocolUserPrompts {}
method acceptAlert
acceptAlert: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Accepts the currently displayed alert dialog. Usually, this is equivalent to clicking on the 'OK' button in the dialog.
Example 1
browser.acceptAlert()
See Also
https://nightwatchjs.org/api/acceptAlert.html
Deprecated
In favour of
.alerts.accept()
.
method dismissAlert
dismissAlert: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Dismisses the currently displayed alert dialog. For confirm() and prompt() dialogs, this is equivalent to clicking the 'Cancel' button.
For alert() dialogs, this is equivalent to clicking the 'OK' button.
Example 1
browser.dismissAlert();
See Also
https://nightwatchjs.org/api/dismissAlert.html
Deprecated
In favour of
.alerts.dismiss()
.
method getAlertText
getAlertText: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<this, string>;
Gets the text of the currently displayed JavaScript alert(), confirm(), or prompt() dialog.
Example 1
browser.getAlertText();
See Also
https://nightwatchjs.org/api/getAlertText.html
Deprecated
In favour of
.alerts.getText()
.
method registerBasicAuth
registerBasicAuth: ( username: string, password: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Automate the input of basic auth credentials whenever they arise.
Example 1
this.demoTest = function (browser) { browser .registerBasicAuth('test-username', 'test-password') .navigateTo('http://browserspy.dk/password-ok.php'); };
See Also
https://nightwatchjs.org/api/registerBasicAuth.html#apimethod-container
method setAlertText
setAlertText: ( value: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Sends keystrokes to a JavaScript prompt() dialog.
Example 1
browser.setAlertText('randomalert');
See Also
https://nightwatchjs.org/api/setAlertText.html
Deprecated
In favour of
.alerts.setText()
.
interface WindowNsCommands
interface WindowNsCommands<ReturnType = unknown> {}
method close
close: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Close the current window or tab. This can be useful when you're working with multiple windows/tabs open (e.g. an OAuth login).
After closing a window or tab, you must switch back to a valid window handle (using
.window.switchTo()
command) in order to continue execution.Example 1
module.exports = { 'close current window/tab': function (browser) { browser.window.close(function (result) { console.log('current window/tab closed successfully'); }); },
'close current window/tab with ES6 async/await': async function (browser) { await browser.window.close(); } };
method fullscreen
fullscreen: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Set the current window state to fullscreen, similar to pressing F11 in most browsers.
Example 1
module.exports = { 'make current window fullscreen': function (browser) { browser.window.fullscreen(function () { console.log('window in fullscreen mode'); }); },
'make current window fullscreen with ES6 async/await': async function (browser) { await browser.window.fullscreen(); } };
method getAllHandles
getAllHandles: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string[]> ) => void) => Awaitable<IfUnknown<ReturnType, this>, string[]>;
Retrieve the list of all window handles available to the session.
Example 1
module.exports = { 'get all window handles': function (browser) { browser.window.getAllHandles(function (result) { console.log('available window handles are:', result.value); }); },
'get all window handles with ES6 async/await': async function (browser) { const windowHandles = await browser.window.getAllHandles(); console.log('available window handles are:', windowHandles); } };
method getHandle
getHandle: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<IfUnknown<ReturnType, this>, string>;
Retrieve the current window handle.
WebDriver does not make the distinction between windows and tabs. So, if your site opens a new tab or window, you can work with it using a window handle.
Example 1
module.exports = { 'get current window handle': function (browser) { browser.window.getHandle(function (result) { console.log('current window handle is:', result.value); }); },
'get current window handle with ES6 async/await': async function (browser) { const windowHandle = await browser.window.getHandle(); console.log('current window handle is:', windowHandle); } };
method getPosition
getPosition: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<WindowPosition> ) => void) => Awaitable<IfUnknown<ReturnType, this>, WindowPosition>;
Get the coordinates of the top left corner of the current window.
Example 1
module.exports = { 'get current window position': function (browser) { browser.window.getPosition(function (result) { console.log('Position of current window:', result.value.x, result.value.y); }); },
'get current window position using ES6 async/await': async function (browser) { const {x, y} = await browser.window.getPosition(); console.log('Position of current window:', x, y); } };
method getRect
getRect: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<WindowSizeAndPosition> ) => void) => Awaitable<IfUnknown<ReturnType, this>, WindowSizeAndPosition>;
Fetches the [window rect](https://w3c.github.io/webdriver/#dfn-window-rect) - size and position of the current window.
Its JSON representation is the following: -
x
- window's screenX attribute; -y
- window's screenY attribute; -width
- outerWidth attribute; -height
- outerHeight attribute.All attributes are in CSS pixels.
Example 1
module.exports = { 'get current window rect': function (browser) { browser.window.getRect(function (result) { console.log('Size of current window:', result.value.width, result.value.height); console.log('Position of current window:', result.value.x, result.value.y); }); },
'get current window rect using ES6 async/await': async function (browser) { const {width, height, x, y} = await browser.window.getRect(); console.log('Size of current window:', width, height); console.log('Position of current window:', x, y); } };
method getSize
getSize: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<WindowSize> ) => void) => Awaitable<IfUnknown<ReturnType, this>, WindowSize>;
Get the size of the current window in pixels.
Example 1
module.exports = { 'get current window size': function (browser) { browser.window.getSize(function (result) { console.log('Size of current window:', result.value.width, result.value.height); }); },
'get current window size using ES6 async/await': async function (browser) { const {width, height} = await browser.window.getSize(); console.log('Size of current window:', width, height); } };
method maximize
maximize: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Increases the window to the maximum available size without going full-screen.
Example 1
module.exports = { 'maximize current window': function (browser) { browser.window.maximize(function () { console.log('window maximized successfully'); }); },
'maximize current window using ES6 async/await': async function (browser) { await browser.window.maximize(); } };
method minimize
minimize: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, 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 1
module.exports = { 'minimize current window': function (browser) { browser.window.minimize(function () { console.log('window minimized successfully'); }); },
'minimize current window using ES6 async/await': async function (browser) { await browser.window.minimize(); } };
method open
open: { ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<IfUnknown<ReturnType, this>, null>; ( type: 'window' | 'tab', callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<IfUnknown<ReturnType, this>, null>;};
Opens a new tab (default) or a separate new window, and changes focus to the newly opened tab/window.
This command is only available for W3C Webdriver compatible browsers.
Example 1
module.exports = { 'open a new tab/window': function (browser) { // open a new tab (default) browser.window.open(function () { console.log('new tab opened successfully'); });
// open a new window browser.window.open('window', function () { console.log('new window opened successfully'); }); },
'open a new tab/window ES6 async demo Test': async function (browser) { // open a new tab (default) await browser.window.open();
// open a new window await browser.window.open('window'); } };
window.openNew
method openNew
openNew: { ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<IfUnknown<ReturnType, this>, null>; ( type: 'window' | 'tab', callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<IfUnknown<ReturnType, this>, null>;};
Opens a new tab (default) or a separate new window, and changes focus to the newly opened tab/window.
This command is only available for W3C Webdriver compatible browsers.
Example 1
module.exports = { 'open a new tab/window': function (browser) { // open a new tab (default) browser.window.openNew(function () { console.log('new tab opened successfully'); });
// open a new window browser.window.openNew('window', function () { console.log('new window opened successfully'); }); },
'open a new tab/window ES6 async demo Test': async function (browser) { // open a new tab (default) await browser.window.openNew();
// open a new window await browser.window.openNew('window'); } };
window.open
method resize
resize: ( width: number, height: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Set the size of the current window in CSS pixels.
Example 1
module.exports = { 'set current window size': function (browser) { browser.window.setSize(1024, 768, function (result) { console.log('window resized successfully'); }); },
'set current window size using ES6 async/await': async function (browser) { await browser.window.setSize(1024, 768); } };
window.setSize
method setPosition
setPosition: ( x: number, y: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Set the position of the current window - move the window to the chosen position.
Example 1
module.exports = { 'set current window position': function (browser) { // Move the window to the top left of the primary monitor browser.window.setPosition(0, 0, function (result) { console.log('window moved successfully'); }); },
'set current window position using ES6 async/await': async function (browser) { // Move the window to the top left of the primary monitor await browser.window.setPosition(0, 0); } };
method setRect
setRect: ( options: WindowSize | WindowPosition | WindowSizeAndPosition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Change the [window rect](https://w3c.github.io/webdriver/#dfn-window-rect) - size and position of the current window.
Its JSON representation is the following: -
x
- window's screenX attribute; -y
- window's screenY attribute; -width
- outerWidth attribute; -height
- outerHeight attribute.All attributes are in CSS pixels.
To change the window rect, you can either specify
width
andheight
together,x
andy
together, or all properties together.Example 1
module.exports = { 'set current window rect': function (browser) { // Change the screenX and screenY attributes of the window rect. browser.window.setRect({x: 500, y: 500});
// Change the outerWidth and outerHeight attributes of the window rect. browser.window.setRect({width: 600, height: 300}); },
'set current window rect using ES6 async/await': async function (browser) { // Change all attributes of the window rect at once. await browser.window.setRect({ width: 600, height: 300, x: 100, y: 100 }); } };
method setSize
setSize: ( width: number, height: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Set the size of the current window in CSS pixels.
Example 1
module.exports = { 'set current window size': function (browser) { browser.window.setSize(1024, 768, function (result) { console.log('window resized successfully'); }); },
'set current window size using ES6 async/await': async function (browser) { await browser.window.setSize(1024, 768); } };
window.resize
method switch
switch: ( windowHandle: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
method switchTo
switchTo: ( windowHandle: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<IfUnknown<ReturnType, this>, null>;
Change focus to another window.
The window to change focus to must be specified by its server assigned window handle. To find out the window handle, use
window.getAllHandles()
command.Example 1
module.exports = { 'switch to another window': function (browser) { browser .navigateTo('https://nightwatchjs.org/__e2e/window/') .click('#openWindowBttn') .waitUntil(function () { // wait until window handle for the new window is available return new Promise((resolve) => { browser.window.getAllHandles(function (result) { resolve(result.value.length === 2); }); }); }) .perform(async function () { const originalWindow = await browser.window.getHandle(); const allWindows = await browser.window.getAllHandles();
// loop through to find the new window handle for (const windowHandle of allWindows) { if (windowHandle !== originalWindow) { await browser.window.switchTo(windowHandle); break; } }
const currentWindow = await browser.window.getHandle(); browser.assert.notEqual(currentWindow, originalWindow); }); },
'switch to another window with ES6 async/await': async function (browser) { await browser.navigateTo('https://nightwatchjs.org/__e2e/window/'); await browser.click('#openWindowBttn');
// wait until window handle for the new window is available await browser.waitUntil(async function () { const windowHandles = await browser.window.getAllHandles();
return windowHandles.length === 2; });
const originalWindow = await browser.window.getHandle(); const allWindows = await browser.window.getAllHandles();
// loop through available windows to find the new window handle for (const windowHandle of allWindows) { if (windowHandle !== originalWindow) { await browser.window.switchTo(windowHandle); break; } }
const currentWindow = await browser.window.getHandle(); await browser.assert.notEqual(currentWindow, originalWindow); } };
window.switch
interface WindowPosition
interface WindowPosition {}
interface WindowSize
interface WindowSize {}
Type Aliases
type Awaitable
type Awaitable<T, V> = Omit<T, 'then'> & PromiseLike<V>;
type Definition
type Definition = ScopedSelector | WebElement;
type DragAndDropDestination
type DragAndDropDestination = | { readonly x: number; readonly y: number } | WebElement;
type ElementAssertionsOptions
type ElementAssertionsOptions = { readonly negated: boolean; readonly nightwatchInstance: NightwatchClient;};
type ElementsAssertionsOptions
type ElementsAssertionsOptions = { readonly negated: boolean; readonly nightwatchInstance: NightwatchClient;};
type EnhancedPageObject
type EnhancedPageObject< Commands = {}, Elements = {}, Sections extends Record<string, PageObjectSection> = {}, Props = {}, URL = string> = PageObjectClientCommands & ElementCommands & NightwatchCustomCommands & EnhancedPageObjectSharedFields< Required<MergeObjectsArray<Commands>>, Required<MergeObjectsArray<Elements>>, Sections, Props, URL > & Required<MergeObjectsArray<Commands>> & { /** * A url or a function returning a url. This is also used internally when the page's navigate() method is called. * * By default, the url property is set to a string type. To set it to a function type instead, the fifth type parameter * of the `EnhancedPageObject` interface can be used: * * ``` * export interface MyPage extends * EnhancedPageObject<{}, typeof elements, {}, {}, () => string> {} * ``` * * See the usage of the `EnhancedPageObject` interface * [here](https://github.com/nightwatchjs-community/nightwatch-typescript-boilerplate/blob/0bf15a6e8735b576b82bce9a7bb5c6beddb14de4/nightwatch/pages/FileUpload.ts#L17) * for reference. * * @example * const homePageObject = browser.page.homePage(); * * googlePage.url; // if string type * googlePage.url(); // if function type */ url: URL;
/** * This command is an alias to url and also a convenience method because when called without any arguments * it performs a call to .url() with passing the value of `url` property on the page object. * Uses `url` protocol command. * * @example * const homePageObject = browser.page.homePage(); * * homePageObject.navigate(); */ navigate( url?: string, callback?: () => void ): EnhancedPageObject<Commands, Elements, Sections, Props, URL>; };
#### [Enhanced Page Object Instances](https://github.com/nightwatchjs/nightwatch/wiki/Page-Object-API#enhanced-page-object-instances) Page object module definitions are used to define page object instances when their respective factory functions within the page reference of the standard command API is called.
const myPageObject = browser.page.MyPage(); // defined in MyPage.js moduleEvery time a factory function like MyPage above is called, a new instance of the page object is instantiated.
type EnhancedSectionInstance
type EnhancedSectionInstance< Commands = {}, Elements = {}, Sections extends Record<string, PageObjectSection> = {}, Props = {}, Parent = unknown> = EnhancedPageObjectSections<Commands, Elements, Sections, Props, Parent> & Commands & ElementCommands & PageObjectClientCommands & Pick<NightwatchCustomCommands, KeysFilter<NightwatchCustomCommands, Function>> & // eslint-disable-line @typescript-eslint/ban-types Pick< NightwatchComponentTestingCommands, 'importScript' | 'launchComponentRenderer' | 'mountComponent' >;
type ExtendDescribeThis
type ExtendDescribeThis<T> = DescribeInstance & { [P in keyof T]?: T[P];};
type KeysFilter
type KeysFilter<T, U> = { [K in keyof T]-?: T[K] extends U ? K : never;}[keyof T];
type LocateStrategy
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';
type NightwatchAssert
type NightwatchAssert = ( passed: boolean, receivedValue?: any, expectedValue?: any, message?: string, abortOnFailure?: boolean, originalStackTrace?: string) => void;
Performs an assertion
type NightwatchCallbackResult
type NightwatchCallbackResult<T> = | NightwatchTypedCallbackResult<T> | NightwatchCallbackResultError;
type NightwatchGenericCallback
type NightwatchGenericCallback<T> = ( this: NightwatchAPI, result: NightwatchCallbackResult<T>) => void;
type NightwatchLogTypes
type NightwatchLogTypes = 'client' | 'driver' | 'browser' | 'server' | 'performance';
type NightwatchPage
type NightwatchPage = { [name: string]: () => EnhancedPageObject<any, any, any>;} & { [name: string]: NightwatchPage;};
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 1
// 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
type NightwatchSizeAndPosition
type NightwatchSizeAndPosition = WindowSizeAndPosition;
type NightwatchTest
type NightwatchTest = (browser?: NightwatchBrowser) => void;
type NightwatchTestHook
type NightwatchTestHook = ( browser: NightwatchBrowser, done: (err?: unknown) => void) => void;
type NightwatchTests
type NightwatchTests = NightwatchTestFunctions;
type ScopedElementRect
type ScopedElementRect = { readonly x: number; readonly y: number; readonly width: number; readonly height: number;};
type ScopedElementSelector
type ScopedElementSelector = | WebElement | ScopedSelector | WebElementPromise | Promise<WebElement | ScopedSelector>;
type ScopedSelector
type ScopedSelector = string | ElementProperties | Element | SeleniumBy | RelativeBy;
type ScopedSelectorObject
type ScopedSelectorObject = Omit< ElementProperties, 'webElement' | 'webElementId' | 'selector'> & { readonly selector: string | By | RelativeBy;};
type ValueAssertionsOptions
type ValueAssertionsOptions = { readonly negated: boolean; readonly nightwatchInstance: NightwatchClient;};
type WaitUntilActions
type WaitUntilActions = | 'selected' | 'visible' | 'disabled' | 'enabled' | 'not.selected' | 'not.visible' | 'not.enabled' | 'present' | 'not.present';
type WaitUntilOptions
type WaitUntilOptions = { action?: WaitUntilActions; timeout?: number; message?: string; selector?: string; retryInterval?: number; abortOnFailure?: boolean;};
type WindowSizeAndPosition
type WindowSizeAndPosition = WindowPosition & WindowSize;
type WindowType
type WindowType = 'tab' | 'window';
Namespaces
namespace global
namespace global {}
variable after
const after: NightwatchBddTestHook;
variable afterEach
const afterEach: NightwatchBddTestHook;
variable app
const app: NightwatchAPI;
variable before
const before: NightwatchBddTestHook;
variable beforeEach
const beforeEach: NightwatchBddTestHook;
variable browser
const browser: NightwatchBrowser;
variable by
const by: any;
variable By
const By: any;
variable context
const context: SuiteFunction;
variable describe
const describe: SuiteFunction;
variable element
const element: ( locator: any, options?: { isComponent?: boolean; type: string }) => ElementGlobal;
variable ensure
const ensure: Ensure;
variable expect
const expect: Expect;
variable it
const it: TestFunction;
variable locateWith
const locateWith: any;
variable specify
const specify: TestFunction;
variable test
const test: TestFunction;
variable xcontext
const xcontext: PendingSuiteFunction;
variable xdescribe
const xdescribe: PendingSuiteFunction;
variable xit
const xit: PendingTestFunction;
variable xspecify
const xspecify: PendingTestFunction;
Package Files (12)
Dependencies (34)
- @nightwatch/chai
- @nightwatch/html-reporter-template
- @nightwatch/nightwatch-inspector
- @types/chai
- @types/selenium-webdriver
- ansi-to-html
- aria-query
- assertion-error
- boxen
- chai-nightwatch
- chalk
- ci-info
- cli-table3
- devtools-protocol
- didyoumean
- dotenv
- ejs
- envinfo
- glob
- jsdom
- lodash
- minimatch
- minimist
- mocha
- nightwatch-axe-verbose
- open
- ora
- piscina
- selenium-webdriver
- semver
- stacktrace-parser
- strip-ansi
- untildify
- uuid
Dev Dependencies (26)
Peer Dependencies (1)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/nightwatch
.
- Markdown[](https://www.jsdocs.io/package/nightwatch)
- HTML<a href="https://www.jsdocs.io/package/nightwatch"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 14718 ms. - Missing or incorrect documentation? Open an issue for this package.