@types/nightwatch
- Version 2.3.30
- Published
- 277 kB
- 3 dependencies
- MIT license
Install
npm i @types/nightwatch
yarn add @types/nightwatch
pnpm add @types/nightwatch
Overview
TypeScript definitions for nightwatch
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
- clearValue()
- click()
- 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()
- sendKeys()
- setAttribute()
- setPassword()
- setValue()
- submitForm()
- takeElementScreenshot()
- updateValue()
- uploadFile()
- waitForElementNotPresent()
- waitForElementNotVisible()
- waitForElementPresent()
- waitForElementVisible()
ElementGlobal
- accessibleName
- arialRole
- 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()
NightwatchGlobals
- abortOnAssertionFailure
- abortOnElementLocateError
- afterTestCase()
- afterTestSuite()
- asyncHookTimeout
- beforeTestCase()
- beforeTestSuite()
- customReporterCallbackTimeout
- onBrowserNavigate()
- onBrowserQuit()
- reporter
- retryAssertionTimeout
- 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
- backwards_compatibility_mode
- custom_assertions_path
- custom_commands_path
- default_reporter
- disable_colors
- disable_global_apis
- disable_typescript
- dotenv
- element_command_retries
- end_session_on_fail
- exclude
- filter
- globals
- globals_path
- live_output
- output_folder
- page_objects_path
- parallel_mode
- parallel_process_delay
- persist_globals
- plugins
- report_network_errors
- report_prefix
- selenium
- skip_testcases_on_fail
- skipgroup
- skiptags
- src_folders
- start_process
- sync_test_names
- tag_filter
- test_runner
- test_settings
- test_workers
- unit_testing_mode
- use_xpath
- webdriver
- window_size
Type Aliases
- Awaitable
- Definition
- EnhancedPageObject
- EnhancedSectionInstance
- ExtendDescribeThis
- GlobalNightwatchTestHook
- GlobalNightwatchTestHookEach
- LocateStrategy
- NightwatchAssert
- NightwatchCallbackResult
- NightwatchLogTypes
- NightwatchPage
- NightwatchSizeAndPosition
- NightwatchTest
- NightwatchTestHook
- NightwatchTests
- WindowSizeAndPosition
- WindowType
Namespaces
Variables
variable _default
const _default: Nightwatch;
variable ELEMENT_KEY
const ELEMENT_KEY: string;
Functions
function globalElement
globalElement: ( locator: Definition | WebElement, 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]: () => any } & { [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;
Interfaces
interface AppiumCommands
interface AppiumCommands {}
method getContext
getContext: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string | null> ) => void) => Awaitable<NightwatchAPI, 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<NightwatchAPI, 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<NightwatchAPI, 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<NightwatchAPI, 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<NightwatchAPI, 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<NightwatchAPI, '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<NightwatchAPI, 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<NightwatchAPI, 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<NightwatchAPI, null>; ( keycode: number, metastate?: number, flags?: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<NightwatchAPI, 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<NightwatchAPI, null>; ( keycode: number, metastate?: number, flags?: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<NightwatchAPI, 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 setContext
setContext: ( context: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<NightwatchAPI, 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<NightwatchAPI, 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<NightwatchAPI, '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<NightwatchAPI, 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 extends NightwatchAssertions, NightwatchNodeAssertions {}
interface ChromeOptions
interface ChromeOptions {}
property args
args?: string[] | undefined;
List of command-line arguments to use when starting Chrome. Arguments with an associated value should be separated by a '=' sign (e.g., ['start-maximized', 'user-data-dir=/tmp/temp_profile']).
property binary
binary?: string | undefined;
Path to the Chrome executable to use (on Mac OS X, this should be the actual binary, not just the app. e.g., '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome')
property debuggerAddress
debuggerAddress?: string | undefined;
An address of a Chrome debugger server to connect to, in the form of <hostname/ip:port>, e.g. '127.0.0.1:38947'
property detach
detach?: boolean | undefined;
Default: false. If false, Chrome will be quit when ChromeDriver is killed, regardless of whether the session is quit. If true, Chrome will only be quit if the session is quit (or closed). Note, if true, and the session is not quit, ChromeDriver cannot clean up the temporary user data directory that the running Chrome instance is using.
property excludeSwitches
excludeSwitches?: string[] | undefined;
List of Chrome command line switches to exclude that ChromeDriver by default passes when starting Chrome. Do not prefix switches with --.
property extensions
extensions?: string[] | undefined;
A list of Chrome extensions to install on startup. Each item in the list should be a base-64 encoded packed Chrome extension (.crx)
property localState
localState?: Record<string, string> | undefined;
A dictionary with each entry consisting of the name of the preference and its value. These preferences are applied to the Local State file in the user data folder.
property minidumpPath
minidumpPath?: string | undefined;
Directory to store Chrome minidumps . (Supported only on Linux.)
property mobileEmulation
mobileEmulation?: Record<string, string> | undefined;
A dictionary with either a value for “deviceName,” or values for “deviceMetrics” and “userAgent.” Refer to Mobile Emulation for more information.
property perfLoggingPrefs
perfLoggingPrefs?: ChromePerfLoggingPrefs | undefined;
An optional dictionary that specifies performance logging preferences. See below for more information.
property prefs
prefs?: Record<string, string> | undefined;
A dictionary with each entry consisting of the name of the preference and its value. These preferences are only applied to the user profile in use.
property windowTypes
windowTypes?: string[] | undefined;
A list of window types that will appear in the list of window handles. For access to elements, include "webview" in this list.
interface ChromePerfLoggingPrefs
interface ChromePerfLoggingPrefs {}
property bufferUsageReportingInterval
bufferUsageReportingInterval?: number | undefined;
Default: 1000. The requested number of milliseconds between DevTools trace buffer usage events. For example, if 1000, then once per second, DevTools will report how full the trace buffer is. If a report indicates the buffer usage is 100%, a warning will be issued.
property enableNetwork
enableNetwork?: boolean | undefined;
Default: true. Whether or not to collect events from Network domain.
property enablePage
enablePage?: boolean | undefined;
Default: true. Whether or not to collect events from Page domain.
property traceCategories
traceCategories?: string | undefined;
A comma-separated string of Chrome tracing categories for which trace events should be collected. An unspecified or empty string disables tracing.
interface ChromiumClientCommands
interface ChromiumClientCommands {}
method captureBrowserConsoleLogs
captureBrowserConsoleLogs: ( onEventCallback: ( event: Pick< Protocol.Runtime.ConsoleAPICalledEvent, 'type' | 'timestamp' | 'args' > ) => void, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<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<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 captureNetworkRequests
captureNetworkRequests: ( onRequestCallback: ( requestParams: Protocol.Network.RequestWillBeSentEvent ) => void, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<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 .captureNetworkRequests((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 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 mockNetworkResponse
mockNetworkResponse: ( urlToIntercept: string, response?: { status?: Protocol.Fetch.FulfillRequestRequest; headers?: { [name: string]: string }; body?: Protocol.Fetch.FulfillRequestRequest; }, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<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 .mockNetworkResponse('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 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 js library into the current page (using the .executeScript() command) to be paired with axeRun to evaluate the axe-core accessibility rules.
Example 1
this.demoTest = function () { browser .url('https://nightwatchjs.org') .axeInject() .axeRun(); };
See Also
https://nightwatchjs.org/api/axeInject.html
method axeRun
axeRun: ( selector?: string, options?: { [key: string]: any }, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Analyzes the current page against applied axe rules.
Parameter selector
CSS selector to scope rule analysis against, will cascade to child elements
Parameter options
Allows configuration of what rules will be run (accessibility standard or rules to enable/disable)
Example 1
this.demoTest = function () { browser .url('https://nightwatchjs.org') .axeInject() .axeRun( 'body', { runOnly: ['color-contrast', 'image-alt'] } ); };
Example 2
this.demoTest = function () { browser .url('https://nightwatchjs.org') .axeInject() .axeRun( 'body', { '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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 Cookie
interface Cookie {}
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 ElementCommands
interface ElementCommands {}
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#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#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 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#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#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#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#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#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#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#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#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 a 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 | WebElement, 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#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#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#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#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#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#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#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 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#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#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 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, time?: number, poll?: number, abortOnFailure?: boolean, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null | ElementResult[]> ) => void, message?: string ): Awaitable<this, null | Error>; ( using: LocateStrategy, selector: any, time?: number, poll?: number, abortOnFailure?: boolean, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ElementResult[]> ) => void, 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
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.api.waitForElementNotPresent('@dialogContainer', function(result) { console.log(result); }); } }
See Also
https://nightwatchjs.org/api/waitForElementNotPresent.html v0.4.0
method waitForElementNotVisible
waitForElementNotVisible: { ( selector: Definition, time?: number, poll?: number, abortOnFailure?: boolean, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void, message?: string ): Awaitable<this, false | Error>; ( using: LocateStrategy, selector: any, time?: number, poll?: number, abortOnFailure?: boolean, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void, 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
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.api.waitForElementNotVisible('@mainDialog', function(result) { console.log(result); }); } }
v0.4.0
See Also
https://nightwatchjs.org/api/waitForElementNotVisible.html
method waitForElementPresent
waitForElementPresent: { ( selector: Definition, time?: number, poll?: number, abortOnFailure?: boolean, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ElementResult[] | null> ) => void, message?: string ): Awaitable<this, ElementResult[] | Error>; ( using: LocateStrategy, selector: any, time?: number, poll?: number, abortOnFailure?: boolean, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ElementResult[]> ) => void, 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
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.api.waitForElementPresent('@featuresList', function(result) { console.log(result); }); } }
See Also
https://nightwatchjs.org/api/waitForElementPresent.html
method waitForElementVisible
waitForElementVisible: { ( selector: Definition, time?: number, poll?: number, abortOnFailure?: boolean, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void, message?: string ): Awaitable<this, true | Error>; ( using: LocateStrategy, selector: any, time?: number, poll?: number, abortOnFailure?: boolean, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void, 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
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 ElementGlobal
interface ElementGlobal extends Element {}
property accessibleName
accessibleName: ElementGlobal['getAccessibleName'];
Get the computed WAI-ARIA label of element.
property arialRole
arialRole: 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: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ElementGlobal[]> ) => void) => Awaitable<NightwatchAPI, ElementGlobal[]>;
method findElement
findElement: ( selector?: Definition, 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: Definition, 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 {}
index signature
[name: string]: EnhancedSectionInstance<any, any, any>;
interface Ensure
interface Ensure {}
method ableToSwitchToFrame
ableToSwitchToFrame: ( frame: number | WebElement | By) => 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: By) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will loop until an element is found with the given locator.
method elementsLocated
elementsLocated: ( locator: By) => 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: