@types/nightwatch
- Version 2.3.31
- Published
- 280 kB
- 4 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 app
const app: NightwatchAPI;
variable browser
const browser: NightwatchAPI;
variable by
const by: any;
variable Capabilities
const Capabilities: any;
variable ELEMENT_KEY
const ELEMENT_KEY: string;
variable Key
const Key: NightwatchKeys;
Functions
function cli
cli: (callback: () => void) => void;
function client
client: ( settings: NightwatchOptions, reporter?: any, argv?: {}, skipInt?: boolean) => import('./lib/core/client');
function CliRunner
CliRunner: (argv?: {}) => import('./lib/runner/cli/cli');
function createClient
createClient: ({ headless, silent, output, useAsync, env, timeout, parallel, reporter, browserName, globals, devtools, debug, enable_global_apis, config, test_settings,}?: CreateClientParams) => NightwatchProgrammaticAPIClient;
Creates a new Nightwatch client that can be used to create WebDriver sessions.
function globalElement
globalElement: ( locator: Definition | WebElement, options?: { isComponent?: boolean; type: string }) => ElementGlobal;
function initClient
initClient: (opts?: {}) => import('./lib/core/client');
function runner
runner: (argv?: {}, done?: () => void, settings?: {}) => Promise<void>;
function runTests
runTests: ( testSource: string | string[], settings?: any, ...args: any[]) => Promise<void>;
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: ( element: WebElement | Element | string, text: string) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the given element's text to equal the given text.
method elementTextMatches
elementTextMatches: ( element: WebElement | Element | string, regex: RegExp) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the given element's text to match a given regular expression.
method stalenessOf
stalenessOf: ( element: WebElement | Element | string) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the given element to become stale. An element is considered stale once it is removed from the DOM, or a new page has loaded.
method titleContains
titleContains: ( substr: string) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the current page's title to contain the given substring.
method titleIs
titleIs: (title: string) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the current page's title to match the given value.
method titleMatches
titleMatches: ( regex: RegExp) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the current page's title to match the given regular expression.
method urlContains
urlContains: ( substrUrl: string) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the current page's url to contain the given substring.
method urlIs
urlIs: (url: string) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the current page's url to match the given value.
method urlMatches
urlMatches: (regex: RegExp) => Awaitable<NightwatchAPI, NightwatchEnsureResult>;
Creates a condition that will wait for the current page's url to match the given regular expression.
interface Expect
interface Expect {}
method component
component: (property: Definition | WebElement) => ExpectElement;
Expect assertions operating on a single component.
method cookie
cookie: (name: string, domain?: string) => ExpectCookie;
Expect assertions operating on a single cookie after retrieving the entire cookie string, using .getCookies().
method element
element: (property: Definition | WebElement) => ExpectElement;
Expect assertions operating on a single element, specified by its CSS/Xpath selector.
method elements
elements: (property: Definition) => ExpectElements;
Expect assertions operating on a collection of elements, specified by a CSS/Xpath selector. So far only .count is available.
method section
section: (property: Definition) => ExpectSection;
Expect assertions operating on a page-object section, specified by '
@section_name
'.
method title
title: () => ExpectTitle;
Retrieves the page title value in order to be used for performing equal, match or contains assertions on it.
method url
url: () => ExpectUrl;
Retrieves the page url value in order to be used for performing equal, match or contains assertions on it.
call signature
(val: Element | WebElement | By | { [ELEMENT_KEY]: string }): ExpectElement;
call signature
(val: any): Chai.Assertion;
interface ExpectAssertions
interface ExpectAssertions<T> extends ExpectLanguageChains<T> {}
property after
after: (ms: number) => Awaitable<T, NightwatchExpectResult>;
property before
before: (ms: number) => Awaitable<T, NightwatchExpectResult>;
property contain
contain: ExpectInclude<T>;
property contains
contains: ExpectInclude<T>;
property endsWith
endsWith: ExpectEndWith<T>;
property endWith
endWith: ExpectEndWith<T>;
property eq
eq: ExpectEqual<T>;
property equal
equal: ExpectEqual<T>;
property equals
equals: ExpectEqual<T>;
property include
include: ExpectInclude<T>;
property includes
includes: ExpectInclude<T>;
property match
match: ExpectMatch<T>;
property matches
matches: ExpectMatch<T>;
property startsWith
startsWith: ExpectStartWith<T>;
property startWith
startWith: ExpectStartWith<T>;
property toBe
toBe: (value: any) => NightwatchAPI;
property toContain
toContain: (value: string) => NightwatchAPI;
property toEndWith
toEndWith: (value: string) => NightwatchAPI;
property toEqual
toEqual: (value: any) => NightwatchAPI;
property toMatch
toMatch: (regexp: RegExp) => NightwatchAPI;
interface ExpectCookie
interface ExpectCookie extends ExpectAssertions<ExpectCookie> {}
interface ExpectElement
interface ExpectElement extends ExpectAssertions<ExpectElement> {}
property active
active: Awaitable<this, NightwatchExpectResult>;
Property that checks if an element is active in the DOM.
property enabled
enabled: Awaitable<this, NightwatchExpectResult>;
Property that checks if an element is currently enabled.
property present
present: Awaitable<this, NightwatchExpectResult>;
Property that checks if an element is present in the DOM.
property selected
selected: Awaitable<this, NightwatchExpectResult>;
Property that checks if an OPTION element, or an INPUT element of type checkbox or radio button is currently selected.
property text
text: Awaitable<this, NightwatchExpectResult>;
Property that retrieves the text contained by an element. Can be chained to check if contains/equals/matches the specified text or regex.
property value
value: Awaitable<this, NightwatchExpectResult>;
Property that retrieves the value (i.e. the value attributed) of an element. Can be chained to check if contains/equals/matches the specified text or regex.
property visible
visible: Awaitable<this, NightwatchExpectResult>;
Property that asserts the visibility of a specified element.
method a
a: (type: string, message?: string) => Awaitable<this, NightwatchExpectResult>;
Checks if the type (i.e. tag name) of a specified element is of an expected value.
method an
an: (type: string, message?: string) => Awaitable<this, NightwatchExpectResult>;
Checks if the type (i.e. tag name) of a specified element is of an expected value.
method attribute
attribute: ( attribute: string, message?: string) => Awaitable<this, NightwatchExpectResult>;
Checks if a given attribute of an element exists and optionally if it has the expected value.
method css
css: ( property: string, message?: string) => Awaitable<this, NightwatchExpectResult>;
Checks a given css property of an element exists and optionally if it has the expected value.
method domProperty
domProperty: ( propertyName: string, message?: string) => Awaitable<this, NightwatchExpectResult>;
Checks if the specified DOM property of a given element is present and has the expected value. For all the available DOM element properties, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element).
method property
property: ( name: string, message?: string) => Awaitable<this, NightwatchExpectResult>;
Checks if a given DOM property of an element has the expected value. For all the available DOM element properties, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element).
interface ExpectElements
interface ExpectElements extends ExpectAssertions<ExpectElements> {}
property count
count: this;
Checks if the number of elements specified by a selector is equal or not to a given value.
interface ExpectEndWith
interface ExpectEndWith<T> {}
call signature
(value: string): Awaitable<T, NightwatchExpectResult>;
interface ExpectEqual
interface ExpectEqual<T> {}
call signature
(value: any): Awaitable<T, NightwatchExpectResult>;
interface ExpectInclude
interface ExpectInclude<T> {}
call signature
(value: string): Awaitable<T, NightwatchExpectResult>;
interface ExpectLanguageChains
interface ExpectLanguageChains<T> {}
property and
and: T;
property at
at: T;
property be
be: T;
property been
been: T;
property deep
deep: T;
Sets the
deep
flag, later to be used by theequal
.
property does
does: T;
property has
has: T;
property have
have: T;
property is
is: T;
property not
not: T;
Negates any of assertions following in the chain.
property of
of: T;
property same
same: T;
property that
that: T;
property to
to: T;
property which
which: T;
property with
with: T;
interface ExpectMatch
interface ExpectMatch<T> {}
call signature
(regexp: RegExp): Awaitable<T, NightwatchExpectResult>;
interface ExpectSection
interface ExpectSection extends ExpectAssertions<ExpectSection>, ExpectElement {}
interface ExpectStartWith
interface ExpectStartWith<T> {}
call signature
(value: string): Awaitable<T, NightwatchExpectResult>;
interface ExpectTitle
interface ExpectTitle extends ExpectAssertions<ExpectTitle> {}
interface ExpectUrl
interface ExpectUrl extends ExpectAssertions<ExpectUrl> {}
interface JSON_WEB_OBJECT
interface JSON_WEB_OBJECT extends ElementResult {}
property getId
getId: () => string;
interface Level
interface Level {}
interface NightwatchAPI
interface NightwatchAPI extends SharedCommands, WebDriverProtocol, NightwatchCustomCommands, NightwatchApiCommands {}
property appium
appium: AppiumCommands;
property assert
assert: Assert;
property baseUrl
baseUrl: string;
property currentTest
currentTest: NightwatchTestSuite;
property ensure
ensure: Ensure;
property expect
expect: Expect;
property globals
globals: NightwatchGlobals;
property Keys
Keys: NightwatchKeys;
property launch_url
launch_url: string;
property launchUrl
launchUrl: string;
property options
options: NightwatchOptions & Pick<NightwatchTestOptions, 'desiredCapabilities'>;
property page
page: NightwatchPage & NightwatchCustomPageObjects;
property sessionId
sessionId: string;
SessionId of the session used by the Nightwatch api.
property verify
verify: Assert;
method actions
actions: (options?: { async?: boolean; bridge?: boolean }) => Actions;
method setSessionId
setSessionId: (sessionId: string) => this;
Override the sessionId used by Nightwatch client with another session id.
interface NightwatchApiCommands
interface NightwatchApiCommands {}
property browserName
readonly browserName: string;
property platformName
readonly platformName: string;
property WEBDRIVER_ELEMENT_ID
readonly WEBDRIVER_ELEMENT_ID: string;
method isAndroid
isAndroid: () => boolean;
method isAppiumClient
isAppiumClient: () => boolean;
Whether or not Nightwatch is being used to connect to an Appium server.
method isChrome
isChrome: () => boolean;
method isEdge
isEdge: () => boolean;
method isFirefox
isFirefox: () => boolean;
method isInternetExplorer
isInternetExplorer: () => boolean;
method isIOS
isIOS: () => boolean;
method isMobile
isMobile: () => boolean;
method isOpera
isOpera: () => boolean;
method isSafari
isSafari: () => boolean;
interface NightwatchAssertion
interface NightwatchAssertion<T, U = any> {}
Abstract assertion class that will subclass all defined assertions
property api
api: NightwatchAPI;
property client
client: NightwatchClientObject;
property expected
expected: (() => T) | T;
property message
message: string;
method command
command: (callback: (result: U) => void) => this;
method failure
failure: (result: U) => boolean;
method pass
pass: (value: T) => any;
method value
value: (result: U) => T;
interface NightwatchAssertions
interface NightwatchAssertions extends NightwatchCommonAssertions, NightwatchCustomAssertions {}
property not
not: Omit<NightwatchAssertions, 'not'>;
Negates any of assertions following in the chain.
interface NightwatchAssertionsError
interface NightwatchAssertionsError {}
interface NightwatchAssertionsResult
interface NightwatchAssertionsResult<T> {}
interface NightwatchBrowser
interface NightwatchBrowser extends NightwatchAPI, NightwatchComponentTestingCommands, NightwatchCustomCommands {}
interface NightwatchCallbackResultError
interface NightwatchCallbackResultError {}
interface NightwatchClientObject
interface NightwatchClientObject {}
property api
api: NightwatchAPI;
property locateStrategy
locateStrategy: LocateStrategy;
property options
options: NightwatchOptions;
property sessionId
sessionId: string | null;
property settings
settings: NightwatchOptions;
interface NightwatchCommonAssertions
interface NightwatchCommonAssertions {}
property NightwatchAssertionsError
NightwatchAssertionsError: NightwatchAssertionsError;
method attributeContains
attributeContains: ( selector: Definition, attribute: string, expected: string, message?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Checks if the given attribute of an element contains the expected value.
this.demoTest = function (browser) {browser.assert.attributeContains('#someElement', 'href', 'google.com');};
method attributeEquals
attributeEquals: ( selector: Definition, attribute: string, expected: string, message?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Checks if the given attribute of an element has the expected value.
this.demoTest = function (browser) {browser.assert.attributeEquals('body', 'data-attr', 'some value');};
method attributeMatches
attributeMatches: ( selector: Definition, attribute: string, regex: string | RegExp, msg?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Check if an element's attribute value matches a regular expression.
Example 1
this.demoTest = function (browser) {browser.assert.attributeMatches('body', 'data-attr', '(value)');};
method containsText
containsText: ( selector: Definition, expectedText: string, message?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Checks if the given element contains the specified text.
this.demoTest = function (browser) {browser.assert.containsText('#main', 'The Night Watch');};Deprecated
In favour of
assert.textContains()
.
method cssClassNotPresent
cssClassNotPresent: ( selector: Definition, className: string, msg?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Checks if the given element does not have the specified CSS class.
this.demoTest = function (browser) {browser.assert.cssClassNotPresent('#main', 'container');};Deprecated
In favour of
assert.not.hasClass()
.
method cssClassPresent
cssClassPresent: ( selector: Definition, className: string, message?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Checks if the given element has the specified CSS class.
this.demoTest = function (browser) {browser.assert.cssClassPresent('#main', 'container');};Deprecated
In favour of
assert.hasClass()
.
method cssProperty
cssProperty: ( selector: Definition, cssProperty: string, expected: string, msg?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Checks if the specified css property of a given element has the expected value.
this.demoTest = function (browser) {browser.assert.cssProperty('#main', 'display', 'block');};
method domPropertyContains
domPropertyContains: ( selector: Definition, domProperty: string, expected: string | number, msg?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<any>>;
Checks if the specified DOM property of a given element has the expected value. For all the available DOM element properties, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element). Several properties can be specified (either as an array or command-separated list). Nightwatch will check each one for presence.
method domPropertyEquals
domPropertyEquals: ( selector: Definition, domProperty: string, expected: string | number, msg?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<any>>;
Checks if the specified DOM property of a given element has the expected value. For all the available DOM element properties, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element). If the result value is JSON object or array, a deep equality comparison will be performed.
method domPropertyMatches
domPropertyMatches: ( selector: Definition, domProperty: string, expected: string | RegExp, msg?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<any>>;
Check if specified DOM property value of a given element matches a regex. For all the available DOM element properties, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element).
method elementNotPresent
elementNotPresent: ( selector: Definition, msg?: string) => Awaitable< NightwatchAPI, NightwatchAssertionsResult<Array<Omit<JSON_WEB_OBJECT, 'getId'>>>>;
Checks if the given element does not exists in the DOM.
Example 1
this.demoTest = function (browser) {browser.assert.elementNotPresent(".should_not_exist");};Deprecated
In favour of
assert.not.elementPresent()
.
method elementPresent
elementPresent: ( selector: Definition, msg?: string) => Awaitable< NightwatchAPI, NightwatchAssertionsResult<Array<Omit<JSON_WEB_OBJECT, 'getId'>>>>;
Checks if the given element exists in the DOM.
this.demoTest = function (browser) {browser.assert.elementPresent("#main");};
method elementsCount
elementsCount: ( selector: Definition, count: number, msg?: string) => Awaitable< NightwatchAPI, NightwatchAssertionsResult<JSON_WEB_OBJECT[]> & { WebdriverElementId: string; }>;
Checks if the number of elements specified by a selector is equal to a given value.
Example 1
this.demoTest = function (browser) { browser.assert.elementsCount('div', 10); browser.assert.not.elementsCount('div', 10); }
method enabled
enabled: ( selector: Definition, message?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<boolean>>;
Checks if the given element is enabled (as indicated by the 'disabled' attribute).
Example 1
this.demoTest = function (browser) { browser.assert.enabled('.should_be_enabled'); browser.assert.enabled({selector: '.should_be_enabled'}); browser.assert.enabled({selector: '.should_be_enabled', suppressNotFoundErrors: true}); };
method hasAttribute
hasAttribute: ( selector: Definition, expectedAttribute: string, msg?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Checks if the given element contains the specified DOM attribute.
Equivalent of: https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttribute
Example 1
this.demoTest = function (browser) {browser.assert.hasAttribute('#main', 'data-track');};
method hasClass
hasClass: ( selector: Definition, className: string | string[], msg?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Checks if the given element has the specified CSS class.
Example 1
this.demoTest = function (browser) {browser.assert.hasClass('#main', 'container');browser.assert.hasClass('#main', ['visible', 'container']);browser.assert.hasClass('#main', 'visible container');};
method hidden
hidden: ( selector: Definition, msg?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<boolean>>;
Checks if the given element is not visible on the page.
Example 1
this.demoTest = function (browser) {browser.assert.hidden('.should_not_be_visible');};Deprecated
In favour of
assert.not.visible()
.
method selected
selected: ( selector: Definition, message?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<boolean>>;
Checks if the given element is selected.
Example 1
this.demoTest = function (browser) { browser.assert.selected('.should_be_selected'); browser.assert.selected({selector: '.should_be_selected'}); browser.assert.selected({selector: '.should_be_selected', suppressNotFoundErrors: true}); };
method textContains
textContains: ( selector: Definition, expectedText: string, msg?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Checks if the given element contains the specified text.
Example 1
this.demoTest = function (browser) {browser.assert.textContains('#main', 'The Night Watch');};
method textEquals
textEquals: ( selector: Definition, expectedText: string, msg?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Check if an element's inner text equals the expected text.
Example 1
this.demoTest = function (browser) {browser.assert.textEquals('#main', 'The Night Watch');};
method textMatches
textMatches: ( selector: Definition, regex: string | RegExp, msg?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Check if an elements inner text matches a regular expression.
Example 1
this.demoTest = function (browser) {browser.assert.textMatches('#main', '^Nightwatch');};
method title
title: ( expected: string, message?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Checks if the page title equals the given value.
this.demoTest = function (browser) {browser.assert.title("Nightwatch.js");};Deprecated
In favour of
titleEquals()
.
method titleContains
titleContains: ( expected: string, message?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Checks if the page title equals the given value.
this.demoTest = function (browser) {browser.assert.title("Nightwatch.js");};
method titleEquals
titleEquals: ( expected: string, message?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Checks if the page title equals the given value. 2.0
this.demoTest = function (browser) {browser.assert.titleEquals("Nightwatch.js");};
method titleMatches
titleMatches: ( regex: string | RegExp, msg?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Checks if the current title matches a regular expression.
Example 1
this.demoTest = function (browser) {browser.assert.titleMatches('^Nightwatch');};
method urlContains
urlContains: ( expectedText: string, message?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Checks if the current URL contains the given value.
this.demoTest = function (browser) {browser.assert.urlContains('google');};
method urlEquals
urlEquals: ( expected: string, message?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Checks if the current url equals the given value.
this.demoTest = function (browser) {browser.assert.urlEquals('https://www.google.com');};
method urlMatches
urlMatches: ( regex: string | RegExp, msg?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Checks if the current url matches a regular expression.
Example 1
this.demoTest = function (browser) {browser.assert.urlMatches('^https');};
method value
value: ( selector: Definition, expectedText: string, message?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Checks if the given form element's value equals the expected value.
this.demoTest = function (browser) {browser.assert.value("form.login input[type=text]", "username");};Deprecated
In favour of
assert.valueEquals()
.
method valueContains
valueContains: ( selector: Definition, expectedText: string, message?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Checks if the given form element's value contains the expected value.
this.demoTest = function (browser) {browser.assert.valueContains("form.login input[type=text]", "username");};
method valueEquals
valueEquals: ( selector: Definition, expected: string, msg?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<string>>;
Checks if the given form element's value equals the expected value.
The existing .assert.value() command.
Example 1
this.demoTest = function (browser) {browser.assert.valueEquals("form.login input[type=text]", "username");};
method visible
visible: ( selector: Definition, message?: string) => Awaitable<NightwatchAPI, NightwatchAssertionsResult<boolean>>;
Checks if the given element is visible on the page.
this.demoTest = function (browser) {browser.assert.visible(".should_be_visible");};
interface NightwatchComponentTestingCommands
interface NightwatchComponentTestingCommands {}
method importScript
importScript: ( scriptPath: string, options: { scriptType: string; componentType: string }, callback: () => void) => this;
method launchComponentRenderer
launchComponentRenderer: () => this;
method mountComponent
mountComponent: ( componentPath: string, props?: string | (() => void), callback?: () => void) => Element;
method mountReactComponent
mountReactComponent: ( componentPath: string, props?: string | (() => void), callback?: () => void) => Element;
method mountVueComponent
mountVueComponent: ( componentPath: string, options?: any, callback?: () => void) => Element;
interface NightwatchCustomAssertions
interface NightwatchCustomAssertions {}
interface NightwatchCustomCommands
interface NightwatchCustomCommands {}
interface NightwatchCustomPageObjects
interface NightwatchCustomPageObjects {}
interface NightwatchDesiredCapabilities
interface NightwatchDesiredCapabilities {}
property acceptSslCerts
acceptSslCerts?: boolean | undefined;
Whether the session should accept all SSL certs by default.
property applicationCacheEnabled
applicationCacheEnabled?: boolean | undefined;
Whether the session can interact with the application cache.
property browserConnectionEnabled
browserConnectionEnabled?: boolean | undefined;
Whether the session can query for the browser's connectivity and disable it if desired.
property browserName
browserName?: string | null;
The name of the browser being used; examples: {chrome|firefox|safari|edge|internet explorer|android|iPhone|iPad|opera|brave}.
property chromeOptions
chromeOptions?: ChromeOptions | undefined;
This is a list of all the Chrome-specific desired capabilities.
property cssSelectorsEnabled
cssSelectorsEnabled?: boolean | undefined;
Whether the session supports CSS selectors when searching for elements.
property databaseEnabled
databaseEnabled?: boolean | undefined;
Whether the session can interact with database storage.
property elementScrollBehaviour
elementScrollBehaviour?: number | undefined;
Allows the user to specify whether elements are scrolled into the viewport for interaction to align with the top (0) or bottom (1) of the viewport. The default value is to align with the top of the viewport. Supported in IE and Firefox (since 2.36)
property handlesAlerts
handlesAlerts?: boolean | undefined;
Whether the session can interact with modal popups, such as window.alert and window.confirm.
property javascriptEnabled
javascriptEnabled?: boolean | undefined;
Whether the session supports executing user supplied JavaScript in the context of the current page (only on HTMLUnitDriver).
property locationContextEnabled
locationContextEnabled?: boolean | undefined;
Whether the session can set and query the browser's location context.
property loggingPrefs
loggingPrefs?: | { browser?: string | undefined; driver?: string | undefined; server?: string | undefined; } | undefined;
A JSON object describing the logging level of different components in the browser, the driver, or any intermediary WebDriver servers. Available values for most loggers are "OFF", "SEVERE", "WARNING", "INFO", "CONFIG", "FINE", "FINER", "FINEST", "ALL". This produces a JSON object looking something like: {"loggingPrefs": {"driver": "INFO", "server": "OFF", "browser": "FINE"}}.
property nativeEvents
nativeEvents?: boolean | undefined;
Whether the session is capable of generating native events when simulating user input.
property platform
platform?: string | undefined;
A key specifying which platform the browser should be running on. This value should be one of {WINDOWS|XP|VISTA|MAC|LINUX|UNIX|ANDROID}. When requesting a new session, the client may specify ANY to indicate any available platform may be used. For more information see [GridPlatforms (https://code.google.com/p/selenium/wiki/GridPlatforms)]
property rotatable
rotatable?: boolean | undefined;
Whether the session can rotate the current page's current layout between portrait and landscape orientations (only applies to mobile platforms).
property takesScreenShot
takesScreenShot?: boolean | undefined;
Whether the session supports taking screenshots of the current page.
property unexpectedAlertBehaviour
unexpectedAlertBehaviour?: string | undefined;
What the browser should do with an unhandled alert before throwing out the UnhandledAlertException. Possible values are "accept", "dismiss" and "ignore"
property version
version?: string | undefined;
The browser version, or the empty string if unknown.
property webStorageEnabled
webStorageEnabled?: boolean | undefined;
Whether the session supports interactions with storage objects (http://www.w3.org/TR/2009/WD-webstorage-20091029/).
interface NightwatchElement
interface NightwatchElement extends WebElement {}
interface NightwatchEnsureResult
interface NightwatchEnsureResult {}
interface NightwatchExpectResult
interface NightwatchExpectResult {}
interface NightwatchGlobals
interface NightwatchGlobals {}
property abortOnAssertionFailure
abortOnAssertionFailure?: boolean | undefined;
this controls whether to abort the test execution when an assertion failed and skip the rest it's being used in waitFor commands and expect assertions true
property abortOnElementLocateError
abortOnElementLocateError?: boolean | undefined;
this controls whether to abort the test execution when an assertion failed and skip the rest it's being used in waitFor commands and expect assertions false
property asyncHookTimeout
asyncHookTimeout?: number | undefined;
controls the timeout time for async hooks. Expects the done() callback to be invoked within this time or an error is thrown 20000
property customReporterCallbackTimeout
customReporterCallbackTimeout?: number | undefined;
controls the timeout value for when executing the global async reporter. Expects the done() callback to be invoked within this time or an error is thrown 20000
property reporter
reporter: (results: any, cb: any) => void;
property retryAssertionTimeout
retryAssertionTimeout?: number | undefined;
Automatically retrying failed assertions - You can tell Nightwatch to automatically retry failed assertions until a given timeout is reached, before the test runner gives up and fails the test.
property suppressWarningsOnMultipleElementsReturned
suppressWarningsOnMultipleElementsReturned: boolean | undefined;
By default a warning is printed if multiple elements are found using the given locate strategy and selector; set this to true to suppress those warnings false
property throwOnMultipleElementsReturned
throwOnMultipleElementsReturned?: boolean | undefined;
this will cause waitFor commands on elements to throw an error if multiple elements are found using the given locate strategy and selector false
property unitTestsTimeout
unitTestsTimeout?: number | undefined;
controls the timeout value for when running async unit tests. Expects the done() callback to be invoked within this time or an error is thrown 2000
property waitForConditionPollInterval
waitForConditionPollInterval?: number | undefined;
this will overwrite the default polling interval (currently 500ms) for waitFor commands and expect assertions that use retry 500
property waitForConditionTimeout
waitForConditionTimeout?: number | undefined;
default timeout value in milliseconds for waitFor commands and implicit waitFor value for expect assertions 5000
method afterTestCase
afterTestCase: (browser: any) => Promise<void>;
method afterTestSuite
afterTestSuite: (browser: any) => Promise<void>;
method beforeTestCase
beforeTestCase: (browser: any) => Promise<void>;
method beforeTestSuite
beforeTestSuite: (browser: any) => Promise<void>;
method onBrowserNavigate
onBrowserNavigate: (browser: any) => Promise<void>;
method onBrowserQuit
onBrowserQuit: (browser: any) => Promise<void>;
index signature
[key: string]: any;
interface NightwatchKeys
interface NightwatchKeys {}
property ADD
ADD: string;
The numpad add (+) key.
property ALT
ALT: string;
The alt key.
property ARROW_DOWN
ARROW_DOWN: string;
The down arrow.
property ARROW_LEFT
ARROW_LEFT: string;
The left arrow.
property ARROW_RIGHT
ARROW_RIGHT: string;
The right arrow.
property ARROW_UP
ARROW_UP: string;
The up arrow.
property BACK_SPACE
BACK_SPACE: string;
The backspace key.
property CANCEL
CANCEL: string;
OS-specific keystroke sequence that performs a cancel action.
property CLEAR
CLEAR: string;
The clear key. This key only appears on full-size Apple keyboards in place of Num Lock key.
property COMMAND
COMMAND: string;
The command (⌘) key.
property CONTROL
CONTROL: string;
The control key.
property DECIMAL
DECIMAL: string;
The numpad decimal (.) key.
property DELETE
DELETE: string;
The delete key.
property DIVIDE
DIVIDE: string;
The numpad divide (/) key.
property DOWN_ARROW
DOWN_ARROW: string;
property END
END: string;
The end key.
property ENTER
ENTER: string;
The enter (numpad) key.
property EQUALS
EQUALS: string;
The equals key.
property ESCAPE
ESCAPE: string;
The escape key.
property F1
F1: string;
The F1 key.
property F10
F10: string;
The F10 key.
property F11
F11: string;
The F11 key.
property F12
F12: string;
The F12 key.
property F2
F2: string;
The F2 key.
property F3
F3: string;
The F3 key.
property F4
F4: string;
The F4 key.
property F5
F5: string;
The F5 key.
property F6
F6: string;
The F6 key.
property F7
F7: string;
The F7 key.
property F8
F8: string;
The F8 key.
property F9
F9: string;
The F9 key.
property HELP
HELP: string;
The help key. This key only appears on older Apple keyboards in place of the Insert key.
property HOME
HOME: string;
The home key.
property INSERT
INSERT: string;
The insert key.
property LEFT_ARROW
LEFT_ARROW: string;
property META
META: string;
The meta (Windows) key.
property MULTIPLY
MULTIPLY: string;
The numpad multiply (*) key.
property NULL
NULL: string;
Releases all held modifier keys.
property NUMPAD0
NUMPAD0: string;
The numpad zero key.
property NUMPAD1
NUMPAD1: string;
The numpad one key.
property NUMPAD2
NUMPAD2: string;
The numpad two key.
property NUMPAD3
NUMPAD3: string;
The numpad three key.
property NUMPAD4
NUMPAD4: string;
The numpad four key.
property NUMPAD5
NUMPAD5: string;
The numpad five key.
property NUMPAD6
NUMPAD6: string;
The numpad six key.
property NUMPAD7
NUMPAD7: string;
The numpad seven key.
property NUMPAD8
NUMPAD8: string;
The numpad eight key.
property NUMPAD9
NUMPAD9: string;
The numpad nine key.
property PAGEDOWN
PAGEDOWN: string;
The page down key.
property PAGEUP
PAGEUP: string;
The page up key.
property PAUSE
PAUSE: string;
The pause key.
property RETURN
RETURN: string;
The return key.
property RIGHT_ARROW
RIGHT_ARROW: string;
property SEMICOLON
SEMICOLON: string;
The semicolon key.
property SEPARATOR
SEPARATOR: string;
The numpad separator (=) key.
property SHIFT
SHIFT: string;
The shift key.
property SPACE
SPACE: string;
The space bar.
property SUBTRACT
SUBTRACT: string;
The numpad subtract (-) key.
property TAB
TAB: string;
The tab key.
property UP_ARROW
UP_ARROW: string;
interface NightwatchLogEntry
interface NightwatchLogEntry {}
interface NightwatchNodeAssertions
interface NightwatchNodeAssertions {}
method deepEqual
deepEqual: ( actual: any, expected: any, message?: string | Error) => Awaitable<NightwatchAPI, NightwatchNodeAssertionsResult | Error>;
method deepStrictEqual
deepStrictEqual: ( actual: any, expected: any, message?: string | Error) => Awaitable<NightwatchAPI, NightwatchNodeAssertionsResult | Error>;
method doesNotMatch
doesNotMatch: ( value: string, regExp: RegExp, message?: string | Error) => Awaitable<NightwatchAPI, NightwatchNodeAssertionsResult | Error>;
method doesNotReject
doesNotReject: ( block: (() => Promise<any>) | Promise<any>, message?: string | Error) => Awaitable<NightwatchAPI, NightwatchNodeAssertionsResult | Error>;
method doesNotThrow
doesNotThrow: ( block: () => any, message?: string | Error) => Awaitable<NightwatchAPI, NightwatchNodeAssertionsResult | Error>;
method equal
equal: ( actual: any, expected: any, message?: string | Error) => Awaitable<NightwatchAPI, NightwatchNodeAssertionsResult | Error>;
method fail
fail: { (message?: string | Error): Awaitable< NightwatchAPI, NightwatchNodeAssertionsResult | Error >; ( actual: any, expected: any, message?: string | Error, operator?: string ): Awaitable<NightwatchAPI, Error | NightwatchNodeAssertionsResult>;};
method ifError
ifError: ( value: any) => Awaitable<NightwatchAPI, NightwatchNodeAssertionsResult | Error>;
method match
match: ( value: string, regExp: RegExp, message?: string | Error) => Awaitable<NightwatchAPI, NightwatchNodeAssertionsResult | Error>;
method notDeepEqual
notDeepEqual: ( actual: any, expected: any, message?: string | Error) => Awaitable<NightwatchAPI, NightwatchNodeAssertionsResult | Error>;
method notDeepStrictEqual
notDeepStrictEqual: ( actual: any, expected: any, message?: string | Error) => Awaitable<NightwatchAPI, NightwatchNodeAssertionsResult | Error>;
method notEqual
notEqual: ( actual: any, expected: any, message?: string | Error) => Awaitable<NightwatchAPI, NightwatchNodeAssertionsResult | Error>;
method notStrictEqual
notStrictEqual: ( actual: any, expected: any, message?: string | Error) => Awaitable<NightwatchAPI, NightwatchNodeAssertionsResult | Error>;
method ok
ok: ( value: any, message?: string | Error) => Awaitable<NightwatchAPI, NightwatchNodeAssertionsResult | Error>;
method rejects
rejects: ( block: (() => Promise<any>) | Promise<any>, message?: string | Error) => Awaitable<NightwatchAPI, NightwatchNodeAssertionsResult | Error>;
method strictEqual
strictEqual: ( actual: any, expected: any, message?: string | Error) => Awaitable<NightwatchAPI, NightwatchNodeAssertionsResult | Error>;
method throws
throws: ( block: () => any, message?: string | Error) => Awaitable<NightwatchAPI, NightwatchNodeAssertionsResult | Error>;
interface NightwatchNodeAssertionsResult
interface NightwatchNodeAssertionsResult {}
interface NightwatchOptions
interface NightwatchOptions {}
property backwards_compatibility_mode
backwards_compatibility_mode?: boolean;
Set this to true to use the v1.x response format for commands when using ES6 async/await false
property custom_assertions_path
custom_assertions_path?: string | string[] | undefined;
Location(s) where custom assertions will be loaded from.
property custom_commands_path
custom_commands_path?: string | string[] | undefined;
Location(s) where custom commands will be loaded from.
property default_reporter
default_reporter?: string;
junit
property disable_colors
disable_colors?: boolean | undefined;
Controls whether or not to disable coloring of the cli output globally.
property disable_global_apis
disable_global_apis?: boolean;
Set this to true to disable the global objects such as element(), browser, by(), expect()
property disable_typescript
disable_typescript: boolean | undefined;
disable support of loading of typescript files for backwards compatibility with test suites.
property dotenv
dotenv?: any;
configuration settings for the dotenv module - a zero-dependency module that loads environment variables from a .env file into process.env. More details on https://www.npmjs.com/package/dotenv
property element_command_retries
element_command_retries?: number;
Interactive element commands such as "click" or "setValue" can be retried if an error occurred (such as an "element not interactable" error)
property end_session_on_fail
end_session_on_fail?: boolean | undefined;
End the session automatically when the test is being terminated, usually after a failed assertion. true
property exclude
exclude?: string[];
An array of folders or file patterns to be skipped (relative to the main source folder).
Example 1
"exclude" : ["excluded-folder"] or: "exclude" : ["test-folder/*-smoke.js"]
property filter
filter?: string;
Folder or file pattern to be used when loading the tests. Files that don't match this pattern will be ignored
Example 1
"filter" : "tests/*-smoke.js"
property globals
globals?: NightwatchGlobals;
An object which will be made available on the main test api, throughout the test execution.
property globals_path
globals_path?: string | undefined;
Location of an external globals module which will be loaded and made available to the test as a property globals on the main client instance. Globals can also be defined/overwritten inside a test_settings environment.
property live_output
live_output?: boolean | undefined;
Used when running in parallel to determine if the output should be collected and displayed at the end.
property output_folder
output_folder?: string | undefined;
The location where the JUnit XML report files will be saved. Set this to false if you want to disable XML reporting.
property page_objects_path
page_objects_path?: string | string[] | undefined;
Location(s) where page object files will be loaded from.
property parallel_mode
parallel_mode?: boolean;
property parallel_process_delay
parallel_process_delay?: number | undefined;
Used when running in parallel to specify the delay (in milliseconds) between starting the child processes
property persist_globals
persist_globals?: boolean | undefined;
persist the same globals object between runs or have a (deep) copy of it per each test; this can be useful when persisting data between test suites is needed, such as a cookie or session information. false
property plugins
plugins: string[];
property report_network_errors
report_network_errors?: boolean;
Ignore network errors (e.g. ECONNRESET errors)
property report_prefix
report_prefix?: string;
property selenium
selenium?: NightwatchSeleniumOptions | undefined;
An object containing Selenium Server related configuration options. See below for details.
property skip_testcases_on_fail
skip_testcases_on_fail?: boolean | undefined;
Skip the remaining test cases from the current test suite, when one test case fails.
property skipgroup
skipgroup?: string;
Skip a group of tests (a subfolder); can be a list of comma-separated values (no space).
property skiptags
skiptags?: string;
Skip tests by tag name; can be a list of comma-separated values (no space).
property src_folders
src_folders: string | string[];
An array of folders (excluding subfolders) where the tests are located.
property start_process
start_process?: boolean | undefined;
Whether or not to automatically start the Selenium/WebDriver session. If running unit tests, this should be set tot false. true
property sync_test_names
sync_test_names?: boolean;
A name property will be added to the desiredCapabilities containing the test suite name when this is enabled. It is useful when using cloud testing services.
property tag_filter
tag_filter?: string | string[];
Tag(s) used/to be used during test execution. Can be a single tag or an array of tags.
property test_runner
test_runner?: string | NightwatchTestRunner | undefined;
Specifies which test runner to use when running the tests. Values can be either default (built in nightwatch runner) or mocha. Example: "test_runner" : {"type" : "mocha", "options" : {"ui" : "tdd"}} 'default'
property test_settings
test_settings: NightwatchTestSettings;
This object contains all the test related options. See below for details.
property test_workers
test_workers?: boolean | NightwatchTestWorker | undefined;
Whether or not to run individual test files in parallel. If set to true, runs the tests in parallel and determines the number of workers automatically. If set to an object, can specify specify the number of workers as "auto" or a number. Example: "test_workers" : {"enabled" : true, "workers" : "auto"} false
property unit_testing_mode
unit_testing_mode?: boolean;
property use_xpath
use_xpath?: boolean;
Use xpath as the default locator strategy.
property webdriver
webdriver?: | { /** * When this is enabled, the Webdriver server is run in background in a child process and started/stopped automatically. * Nightwatch includes support for managing Chromedriver, Geckodriver (Firefox), Safaridriver, and Selenium Server. Please refer to the Install Webdriver section for details. * @default false */ start_process: boolean;
/** * Only useful if start_process is enabled. * @default none */ server_path: string;
/** * Only needed when the Webdriver service is running on a different machine. */ host: string;
/** * The port number on which the Webdriver service will listen and/or on which Nightwatch will attempt to connect. */ port: number;
/** * Should be set to true if connecting to a remote (cloud) service via HTTPS. Also don't forget to set port to 443. */ ssl: boolean;
/** * The location where the Webdriver service log file output.log file will be placed. Defaults to current directory. * To disable Webdriver logging, set this to false. * @default none */ log_path: string | boolean;
/** * List of cli arguments to be passed to the Webdriver process. This varies for each Webdriver implementation. * * @default none */ cli_args: any;
/** * Some Webdriver implementations (Safari, Edge) support both the W3C Webdriver API as well as the legacy JSON Wire (Selenium) API. * * @default false */ use_legacy_jsonwire: boolean;
/** * Time to wait (in ms) before starting to check the Webdriver server is up and running. * * @default 100 */ check_process_delay: number;
/** * Maximum number of ping status check attempts when checking if the Webdriver server is up and running before returning a timeout error. * * @default 5 */ max_status_poll_tries: number;
/** * Interval (in ms) to use between status ping checks when checking if the Webdriver server is up and running. * * @default 100 */ status_poll_interval: number;
/** * The entire time (in ms) to wait for the Node.js process to be created and running (default is 2 min), including spawning the child process and checking the status. * * @default 120000 */ process_create_timeout: number;
/** * Proxy requests to the Webdriver (or Selenium) service. http, https, socks(v5), socks5, sock4, and pac are accepted. Uses node-proxy-agent. * * @example http://user:pass@host:port * @default none */ proxy: string;
/** * Requests to the Webdriver service will timeout in timeout miliseconds; a retry will happen retry_attempts number of times. * * @example {timeout: 15000, retry_attempts: 5} */ timeout_options: TimeoutOptions;
/** * Needed sometimes when using a Selenium Server. The prefix to be added to to all requests (e.g. /wd/hub). */ default_path_prefix: string;
/** * Usually only needed for cloud testing Selenium services. In case the server requires credentials this username will be used to compute the Authorization header. * * The value can be also an environment variable, in which case it will look like this: * "username" : "${SAUCE_USERNAME}" * * @default none */ username: string;
/** * This field will be used together with username to compute the Authorization header. * * Like username, the value can be also an environment variable: * "access_key" : "${SAUCE_ACCESS_KEY}" * * @default none */ access_key: string;
/** * Sets the path to the Chrome binary to use. * On Mac OS X, this path should reference the actual Chrome executable, * not just the application binary (e.g. "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"). */ chrome_binary?: '';
/** * Sets the path to Chrome's log file. This path should exist on the machine that will launch Chrome. */ chrome_log_file?: '';
/** * Configures the ChromeDriver to launch Chrome on Android via adb. */ android_chrome?: false;
/** * Sets the path to the Edge binary to use. This path should exist on the machine that will launch Edge. */ edge_binary?: '';
/** * Sets the path to the Edge binary to use. */ edge_log_file?: '';
/** * Sets the binary to use. The binary may be specified as the path to a Firefox executable or a desired release Channel. This path should exist on the machine that will launch Firefox. */ firefox_binary?: '';
/** * Sets the path to an existing profile to use as a template for new browser sessions. * This profile will be copied for each new session - changes will not be applied to the profile itself. */ firefox_profile?: ''; } | undefined;
Allows for webdriver config (mostly the same as selenium)
property window_size
window_size?: WindowSize;
Sets the initial window size: {height: number, width: number}
interface NightwatchPosition
interface NightwatchPosition extends WindowPosition {}
interface NightwatchProgrammaticAPIClient
interface NightwatchProgrammaticAPIClient {}
property nightwatch_client
nightwatch_client: NightwatchClient;
property settings
settings: NightwatchOptions;
method launchBrowser
launchBrowser: () => Promise<NightwatchAPI>;
Create a new browser session.
method updateCapabilities
updateCapabilities: (value: {} | (() => {})) => void;
Update the initially specified capabilities.
interface NightwatchScreenshotOptions
interface NightwatchScreenshotOptions {}
property enabled
enabled?: boolean | undefined;
property filename_format
filename_format: ({ testSuite, testCase, isError, dateObject,}?: { testSuite?: string; testCase?: string; isError?: boolean; dateObject?: Date;}) => string;
property on_error
on_error?: boolean | undefined;
property on_failure
on_failure?: boolean | undefined;
property path
path?: string | undefined;
interface NightwatchSeleniumOptions
interface NightwatchSeleniumOptions {}
property check_process_delay
check_process_delay: number;
Time to wait (in ms) before starting to check the Webdriver server is up and running 500
property cli_args
cli_args: {};
List of cli arguments to be passed to the Selenium process. Here you can set various options for browser drivers, such as:
webdriver.firefox.profile: Selenium will be default create a new Firefox profile for each session. If you wish to use an existing Firefox profile you can specify its name here. Complete list of Firefox Driver arguments available https://code.google.com/p/selenium/wiki/FirefoxDriver.
webdriver.chrome.driver: Nightwatch can run the tests using Chrome browser also. To enable this you have to download the ChromeDriver binary (http://chromedriver.storage.googleapis.com/index.html) and specify it's location here. Also don't forget to specify chrome as the browser name in the desiredCapabilities object. More information can be found on the ChromeDriver website (https://sites.google.com/a/chromium.org/chromedriver/).
webdriver.ie.driver: Nightwatch has support for Internet Explorer also. To enable this you have to download the IE Driver binary (https://code.google.com/p/selenium/wiki/InternetExplorerDriver) and specify it's location here. Also don't forget to specify "internet explorer" as the browser name in the desiredCapabilities object.
property host
host: string;
Usually not required and only used if start_process is true. Specify the IP address you wish Selenium to listen on.
property log_path
log_path: string | boolean;
The location where the selenium Selenium-debug.log file will be placed. Defaults to current directory. To disable Selenium logging, set this to false
property max_status_poll_tries
max_status_poll_tries: number;
Maximum number of ping status check attempts before returning a timeout error 15
property port
port: number | undefined;
The port number Selenium will listen on.
property server_path
server_path: string;
The location of the selenium jar file. This needs to be specified if start_process is enabled.E.g.: lib/selenium-server-standalone-2.43.0.jar
property start_process
start_process: boolean;
Whether or not to manage the selenium process automatically. false
property start_session
start_session: boolean;
Whether or not to automatically start the Selenium session.
property status_poll_interval
status_poll_interval: number;
Interval (in ms) to use between status ping checks when checking if the Webdriver server is up and running 200
interface NightwatchServerStatusResult
interface NightwatchServerStatusResult {}
interface NightwatchSize
interface NightwatchSize extends WindowSize {}
interface NightwatchTestFunctions
interface NightwatchTestFunctions {}
property "@disabled"
'@disabled'?: boolean | undefined;
property "@tags"
'@tags'?: string | string[] | undefined;
property after
after?: NightwatchTestHook | undefined;
property afterEach
afterEach?: NightwatchTestHook | undefined;
property before
before?: NightwatchTestHook | undefined;
property beforeEach
beforeEach?: NightwatchTestHook | undefined;
index signature
[key: string]: any;
interface NightwatchTestHooks
interface NightwatchTestHooks extends NightwatchGlobals {}
property after
after?: GlobalNightwatchTestHook | undefined;
property afterEach
afterEach?: GlobalNightwatchTestHookEach | undefined;
property before
before?: GlobalNightwatchTestHook | undefined;
property beforeEach
beforeEach?: GlobalNightwatchTestHookEach | undefined;
interface NightwatchTestOptions
interface NightwatchTestOptions extends NightwatchTestSettingGeneric {}
property screenshots
screenshots: boolean;
property screenshotsPath
screenshotsPath: string;
interface NightwatchTestRunner
interface NightwatchTestRunner {}
interface NightwatchTestSettingGeneric
interface NightwatchTestSettingGeneric {}
property access_key
access_key?: string | undefined;
This field will be used together with username to compute the Authorization header. Like username, the value can be also an environment variable: "access_key" : "${SAUCE_ACCESS_KEY}"
property cli_args
cli_args?: any;
Same as Selenium settings cli_args. You can override the global cli_args on a per-environment basis.
property desiredCapabilities
desiredCapabilities?: NightwatchDesiredCapabilities | undefined;
An object which will be passed to the Selenium WebDriver when a new session will be created. You can specify browser name for instance along with other capabilities. Example: "desiredCapabilities" : { "browserName" : "firefox", "acceptSslCerts" : true } You can view the complete list of capabilities https://code.google.com/p/selenium/wiki/DesiredCapabilities.
property disable_colors
disable_colors?: boolean | undefined;
Use to disable colored output in the terminal.
property end_session_on_fail
end_session_on_fail?: boolean | undefined;
End the session automatically when the test is being terminated, usually after a failed assertion.
property exclude
exclude?: string[] | undefined;
An array of folders or file patterns to be skipped (relative to the main source folder). Example: "exclude" : ["excluded-folder"] or: "exclude" : ["test-folder/*-smoke.js"]
property filter
filter?: string | undefined;
Folder or file pattern to be used when loading the tests. Files that don't match this patter will be ignored. Example: "filter" : "tests/*-smoke.js"
property globals
globals?: NightwatchTestHooks | undefined;
An object which will be made available within the test and can be overwritten per environment. Example:"globals" : { "myGlobal" : "some_global" }
property launch_url
launch_url?: string | undefined;
A url which can be used later in the tests as the main url to load. Can be useful if your tests will run on different environments, each one with a different url.
property log_screenshot_data
log_screenshot_data?: boolean | undefined;
Do not show the Base64 image data in the (verbose) log when taking screenshots.
property output
output?: boolean | undefined;
Use to disable terminal output completely.
property proxy
proxy?: string | undefined;
Proxy requests to the selenium server. http, https, socks(v5), socks5, sock4, and pac are accepted. Uses node-proxy-agent. Example: http://user:pass@host:port
property selenium_host
selenium_host?: string | undefined;
The hostname/IP on which the selenium server is accepting connections.
property selenium_port
selenium_port?: number | undefined;
The port number on which the selenium server is accepting connections.
property silent
silent?: boolean | undefined;
Whether to show extended Selenium command logs.
property skip_testcases_on_fail
skip_testcases_on_fail?: boolean | undefined;
Skip the rest of testcases (if any) when one testcase fails..
property use_xpath
use_xpath?: boolean | undefined;
Use xpath as the default locator strategy
property username
username?: string | undefined;
In case the selenium server requires credentials this username will be used to compute the Authorization header. The value can be also an environment variable, in which case it will look like this: "username" : "${SAUCE_USERNAME}"
interface NightwatchTestSettings
interface NightwatchTestSettings {}
index signature
[key: string]: NightwatchTestSettingScreenshots;
interface NightwatchTestSettingScreenshots
interface NightwatchTestSettingScreenshots extends NightwatchTestSettingGeneric {}
property screenshots
screenshots: NightwatchScreenshotOptions;
Selenium generates screenshots when command errors occur. With on_failure set to true, also generates screenshots for failing or erroring tests. These are saved on the disk. Since v0.7.5 you can disable screenshots for command errors by setting "on_error" to false. Example: "screenshots" : { "enabled" : true, "on_failure" : true, "on_error" : false, "path" : "" }
interface NightwatchTestSuite
interface NightwatchTestSuite {}
interface NightwatchTestWorker
interface NightwatchTestWorker {}
property enabled
enabled: boolean;
property node_options
node_options?: string | string[] | undefined;
property workers
workers: string | number;
interface NightwatchTypedCallbackResult
interface NightwatchTypedCallbackResult<T> {}
interface PageElements
interface PageElements {}
Map of DOM element locators as shorthand string selectors based on global selector setting or ElementLocator
Example 1
const elements: PageElements { header: "h1", banner: { locateStrategy: "css selector", selector: "#bannerId" } }
index signature
[key: string]: Definition;
interface PageObjectModel
interface PageObjectModel {}
Type for defining page object models allowing for optional type-safe inclusion of url, elements, sections, commands, and props properties.
interface SharedCommands
interface SharedCommands extends ClientCommands, ElementCommands {}
interface TimeoutOptions
interface TimeoutOptions {}
property retry_attempts
retry_attempts: number;
0
property timeout
timeout: number;
60000
interface WebDriverProtocol
interface WebDriverProtocol extends WebDriverProtocolSessions, WebDriverProtocolNavigation, WebDriverProtocolCommandContexts, WebDriverProtocolElements, WebDriverProtocolElementState, WebDriverProtocolElementInteraction, WebDriverProtocolElementLocation, WebDriverProtocolDocumentHandling, WebDriverProtocolCookies, WebDriverProtocolUserActions, WebDriverProtocolUserPrompts, WebDriverProtocolScreenCapture, WebDriverProtocolMobileRelated {}
interface WebDriverProtocolCommandContexts
interface WebDriverProtocolCommandContexts {}
method frame
frame: { ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( frameId: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Change focus to another frame on the page. If the frame id is missing or null, the server should switch to the page's default content.
Example 1
this.demoTest = function (browser) { browser.frame('', function(result) { console.log(result); }); }
See Also
https://nightwatchjs.org/api/frame.html
method frameParent
frameParent: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Change focus to the parent context. If the current context is the top level browsing context, the context remains unchanged.
Example 1
this.demoTest = function (browser) { browser.frameParent(function(result) { console.log(result); }); }
v0.4.8
See Also
https://nightwatchjs.org/api/frameParent.html
method window
window: ( method: 'post' | 'delete' | 'POST' | 'DELETE', handleOrName?: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Change focus to another window or close the current window. Shouldn't normally be used directly, instead
.switchWindow()
and.closeWindow()
should be used.See Also
https://nightwatchjs.org/api/window.html
Deprecated
Use
.switchWindow()
and.closeWindow()
instead.
method windowHandle
windowHandle: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<this, string>;
Retrieve the current window handle.
Example 1
this.demoTest = function (browser) { browser.windowHandle(function(result) { console.log(result.value); }); }
See Also
https://nightwatchjs.org/api/windowHandle.html
method windowHandles
windowHandles: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string[]> ) => void) => Awaitable<this, string[]>;
Retrieve the list of all window handles available to the session.
Example 1
this.demoTest = function (browser) { browser.windowHandles(function(result) { // An array of window handles. console.log(result.value); }); }
See Also
https://nightwatchjs.org/api/windowHandles.html
method windowMaximize
windowMaximize: ( handleOrName?: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Increases the window to the maximum available size without going full-screen.
Example 1
this.demoTest = function (browser) { browser.windowMaximize('current', function(result) { console.log(result); }); }
See Also
https://nightwatchjs.org/api/windowMaximize.html
method windowPosition
windowPosition: { ( windowHandle: string, offsetX: number, offsetY: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( windowHandle: string, callback: ( this: NightwatchAPI, result: NightwatchCallbackResult<WindowPosition> ) => void ): Awaitable<this, WindowPosition>;};
Change or get the position of the specified window. If the second argument is a function it will be used as a callback and the call will perform a get request to retrieve the existing window position.
Example 1
this.demoTest = function (browser) {
// Change the position of the specified window. // If the :windowHandle URL parameter is "current", the currently active window will be moved. browser.windowPosition('current', 0, 0, function(result) { console.log(result); });
// Get the position of the specified window. // If the :windowHandle URL parameter is "current", the position of the currently active window will be returned. browser.windowPosition('current', function(result) { console.log(result.value); }); }
See Also
https://nightwatchjs.org/api/windowPosition.html
method windowRect
windowRect: { ( options: { width?: number; height?: number; x?: number; y?: number }, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( options: null, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<WindowSizeAndPosition> ) => void ): Awaitable<this, WindowSizeAndPosition>;};
Change or get the [window rect](https://w3c.github.io/webdriver/#dfn-window-rect). This is defined as a dictionary of the
screenX
,screenY
,outerWidth
andouterHeight
attributes of the window.Its JSON representation is the following: -
x
- window's screenX attribute; -y
- window's screenY attribute; -width
- outerWidth attribute; -height
- outerHeight attribute.All attributes are in in CSS pixels. To change the window react, you can either specify
width
andheight
,x
andy
or all properties together.Example 1
module.exports = { 'demo test .windowRect()': function(browser) {
// Change the screenX and screenY attributes of the window rect. browser.windowRect({x: 500, y: 500});
// Change the width and height attributes of the window rect. browser.windowRect({width: 600, height: 300});
// Retrieve the attributes browser.windowRect(function(result) { console.log(result.value); }); },
'windowRect ES6 demo test': async function(browser) { const resultValue = await browser.windowRect(); console.log('result value', resultValue); } }
See Also
https://nightwatchjs.org/api/windowRect.html
method windowSize
windowSize: { ( windowHandle: string, width: number, height: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( windowHandle: string, callback: ( this: NightwatchAPI, result: NightwatchCallbackResult<WindowSizeAndPosition> ) => void ): Awaitable<this, WindowSizeAndPosition>;};
Change or get the size of the specified window. If the second argument is a function it will be used as a callback and the call will perform a get request to retrieve the existing window size.
Example 1
this.demoTest = function (browser) {
// Return the size of the specified window. If the :windowHandle URL parameter is "current", the size of the currently active window will be returned. browser.windowSize('current', function(result) { console.log(result.value); });
// Change the size of the specified window. // If the :windowHandle URL parameter is "current", the currently active window will be resized. browser.windowSize('current', 300, 300, function(result) { console.log(result.value); }); }
See Also
https://nightwatchjs.org/api/windowSize.html
interface WebDriverProtocolCookies
interface WebDriverProtocolCookies {}
method cookie
cookie: { ( method: 'GET' | 'DELETE', callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<Cookie[] | null> ) => void ): Awaitable<this, Cookie[] | null>; ( method: 'POST', cookie: Cookie, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( method: 'DELETE', cookieName: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Retrieve or delete all cookies visible to the current page or set a cookie. Normally this shouldn't be used directly, instead the cookie convenience methods should be used: getCookie, getCookies, setCookie, deleteCookie, deleteCookies.
See Also
getCookies
getCookie
setCookie
deleteCookie
deleteCookies
interface WebDriverProtocolDocumentHandling
interface WebDriverProtocolDocumentHandling {}
method execute
execute: { <ReturnValue>( body: ExecuteScriptFunction<[], ReturnValue> | string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<VoidToNull<ReturnValue>> ) => void ): Awaitable<this, VoidToNull<ReturnValue>>; <ArgType extends any[], ReturnValue>( body: string | ExecuteScriptFunction<ArgType, ReturnValue>, args: ArgType, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<VoidToNull<ReturnValue>> ) => void ): Awaitable<this, VoidToNull<ReturnValue>>;};
Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be synchronous. The script argument defines the script to execute in the form of a function body. The value returned by that function will be returned to the client.
The function will be invoked with the provided args array and the values may be accessed via the arguments object in the order specified.
Under the hood, if the
body
param is a function it is converted to a string with<function>.toString()
. Any references to your current scope are ignored.To ensure cross-browser compatibility, the specified function should not be in ES6 format (i.e.
() => {}
). If the execution of the function fails, the first argument of the callback contains error information.Example 1
this.demoTest = function (browser) { browser.execute(function(imageData: string) { // resize operation return true; }, [imageData], function(result) { // result.value === true }); }
See Also
https://nightwatchjs.org/api/execute.html#apimethod-container
executeScript
method executeAsync
executeAsync: { <ReturnValue>( script: ExecuteAsyncScriptFunction<[], ReturnValue> | string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ReturnValue> ) => void ): Awaitable<this, ReturnValue>; <ArgType extends any[], ReturnValue>( script: string | ExecuteAsyncScriptFunction<ArgType, ReturnValue>, args: ArgType, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ReturnValue> ) => void ): Awaitable<this, ReturnValue>;};
Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be asynchronous.
The function to be injected receives the
done
callback as argument which needs to be called when the asynchronous operation finishes. The value passed to thedone
callback is returned to the client. Additional arguments for the injected function may be passed as a non-empty array which will be passed before thedone
callback.Asynchronous script commands may not span page loads. If an unload event is fired while waiting for the script result, an error will be returned.
Example 1
this.demoTest = function (browser) { browser.executeAsync(function(done: (result: true) => void) { setTimeout(function() { done(true); }, 500); }, function(result) { // result.value === true });
browser.executeAsync(function(arg1: string, arg2: number, done: (result: string) => void) { setTimeout(function() { done(arg1); }, 500); }, [arg1, arg2], function(result) { // result.value === arg1 }); }
See Also
https://nightwatchjs.org/api/executeAsyncScript.html
executeAsyncScript
method executeAsyncScript
executeAsyncScript: { <ReturnValue>( script: ExecuteAsyncScriptFunction<[], ReturnValue> | string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ReturnValue> ) => void ): Awaitable<this, ReturnValue>; <ArgType extends any[], ReturnValue>( script: string | ExecuteAsyncScriptFunction<ArgType, ReturnValue>, args: ArgType, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ReturnValue> ) => void ): Awaitable<this, ReturnValue>;};
Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be asynchronous.
The function to be injected receives the
done
callback as argument which needs to be called when the asynchronous operation finishes. The value passed to thedone
callback is returned to the client. Additional arguments for the injected function may be passed as a non-empty array which will be passed before thedone
callback.Asynchronous script commands may not span page loads. If an unload event is fired while waiting for the script result, an error will be returned.
Example 1
this.demoTest = function (browser) { browser.executeAsyncScript(function(done: (result: true) => void) { setTimeout(function() { done(true); }, 500); }, function(result) { // result.value === true });
browser.executeAsyncScript(function(arg1: string, arg2: number, done: (result: string) => void) { setTimeout(function() { done(arg1); }, 500); }, [arg1, arg2], function(result) { // result.value === arg1 }); }
See Also
https://nightwatchjs.org/api/executeAsyncScript.html
executeAsync
method executeScript
executeScript: { <ReturnValue>( body: ExecuteScriptFunction<[], ReturnValue> | string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<VoidToNull<ReturnValue>> ) => void ): Awaitable<this, VoidToNull<ReturnValue>>; <ArgType extends any[], ReturnValue>( body: string | ExecuteScriptFunction<ArgType, ReturnValue>, args: ArgType, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<VoidToNull<ReturnValue>> ) => void ): Awaitable<this, VoidToNull<ReturnValue>>;};
Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be synchronous. The script argument defines the script to execute in the form of a function body. The value returned by that function will be returned to the client.
The function will be invoked with the provided args array and the values may be accessed via the arguments object in the order specified.
Under the hood, if the
body
param is a function it is converted to a string with<function>.toString()
. Any references to your current scope are ignored.To ensure cross-browser compatibility, the specified function should not be in ES6 format (i.e.
() => {}
). If the execution of the function fails, the first argument of the callback contains error information.Example 1
this.demoTest = function (browser) { browser.executeScript(function(imageData: string) { // resize operation return true; }, [imageData], function(result) { // result.value === true }); }
See Also
https://nightwatchjs.org/api/execute.html#apimethod-container
execute
method source
source: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<this, string>;
Returns a string serialisation of the DOM of the current page.
Example 1
browser.source();
See Also
https://nightwatchjs.org/api/source.html#apimethod-container
interface WebDriverProtocolElementInteraction
interface WebDriverProtocolElementInteraction {}
method elementIdClear
elementIdClear: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Scrolls into view a submittable element excluding buttons or editable element, and then attempts to clear its value, reset the checked state, or text content.
Example 1
browser.elementIdClear(elementId);
See Also
https://nightwatchjs.org/api/elementIdClear.html#apimethod-container
method elementIdClick
elementIdClick: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Scrolls into view the element and clicks the in-view center point. If the element is not pointer-interactable, an element not interactable error is returned.
Example 1
browser.elementIdClick(elementId);
See Also
https://nightwatchjs.org/api/elementIdClick.html#apimethod-container
method elementIdValue
elementIdValue: { ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>; ( id: string, value: string | string[], callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Scrolls into view the form control element and then sends the provided keys to the element, or returns the current value of the element. In case the element is not keyboard interactable, an element not interactable error is returned.
See Also
https://nightwatchjs.org/api/elementIdValue.html#apimethod-container
Deprecated
In favour of .getValue() and .setValue()
method keys
keys: ( keysToSend: string | string[], callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Send a sequence of key strokes to the active element. The sequence is defined in the same format as the
sendKeys
command. An object map with available keys and their respective UTF-8 characters, as defined on [W3C WebDriver draft spec](https://www.w3.org/TR/webdriver/#character-types), is loaded onto the main Nightwatch instance asclient.Keys
.Rather than the
setValue
, the modifiers are not released at the end of the call. The state of the modifier keys is kept between calls, so mouse interactions can be performed while modifier keys are depressed.Since v2.0, this command is deprecated. It is only available on older JSONWire-based drivers. Please use the new [User Actions API](https://nightwatchjs.org/api/useractions/#overview).
Example 1
browser .keys(browser.Keys.CONTROL) // hold down CONTROL key .click('#element') .keys(browser.Keys.NULL) // release all keys
See Also
https://nightwatchjs.org/api/keys.html#apimethod-container
Deprecated
Please use the [User Actions API](https://nightwatchjs.org/api/useractions/#overview) API instead
method submit
submit: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Submit a FORM element. The submit command may also be applied to any element that is a descendant of a FORM element.
Example 1
browser.submit(elementID);
interface WebDriverProtocolElementLocation
interface WebDriverProtocolElementLocation {}
method elementIdLocation
elementIdLocation: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchSizeAndPosition> ) => void) => Awaitable<this, NightwatchSizeAndPosition>;
Determine an element's location on the page. The point (0, 0) refers to the upper-left corner of the page.
The element's coordinates are returned as a JSON object with x and y properties.
See Also
https://nightwatchjs.org/api/elementIdLocation.html#apimethod-container
Deprecated
In favour of .getElementRect()
method elementIdLocationInView
elementIdLocationInView: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchPosition> ) => void) => Awaitable<this, NightwatchPosition>;
Determine an element's location on the screen once it has been scrolled into view.
See Also
https://nightwatchjs.org/api/elementIdLocationInView.html#apimethod-container
Deprecated
This is a JSON Wire Protocol command and is no longer supported.
interface WebDriverProtocolElements
interface WebDriverProtocolElements {}
method element
element: ( using: LocateStrategy, value: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ElementResult> ) => void) => Awaitable<this, ElementResult>;
Search for an element on the page, starting from the document root. The located element will be returned as a web element JSON object. First argument to be passed is the locator strategy, which is detailed on the [WebDriver docs](https://www.w3.org/TR/webdriver/#locator-strategies).
The locator stragy can be one of: -
css selector
-link text
-partial link text
-tag name
-xpath
Example 1
module.exports = { 'demo Test' : function(browser) { browser.element('css selector', 'body', function(result) { console.log(result.value) }); },
'es6 async demo Test': async function(browser) { const result = await browser.element('css selector', 'body'); console.log('result value is:', result); },
'demo Test with page object': function(browser) { const loginPage = browser.page.login(); loginPage.api.element('@resultContainer', function(result) { console.log(result.value) }); } }
See Also
https://nightwatchjs.org/api/element.html
method elementActive
elementActive: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<this, string>;
Get the element on the page that currently has focus. The element will be returned as a [Web Element](https://www.w3.org/TR/webdriver1/#dfn-web-elements) id.
Example 1
module.exports = { 'demo Test' : function(browser) { browser.elementActive(function(result) { console.log(result.value) }); } }
See Also
https://nightwatchjs.org/api/elementActive.html
method elementIdDoubleClick
elementIdDoubleClick: ( webElementId: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Move to the element and performs a double-click in the middle of the given element if element is given else double-clicks at the current mouse coordinates (set by
.moveTo()
).
method elementIdElement
elementIdElement: ( id: string, using: LocateStrategy, value: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ElementResult | []> ) => void) => Awaitable<this, ElementResult | []>;
Search for an element on the page, starting from the identified element. The located element will be returned as a Web Element JSON object.
This command operates on a protocol level and requires a [Web Element ID](https://www.w3.org/TR/webdriver1/#dfn-web-elements). Read more on [Element retrieval](https://www.w3.org/TR/webdriver1/#element-retrieval) on the W3C WebDriver spec page.
Example 1
module.exports = { 'demo Test' : function(browser) { browser.findElement('.some-element', (result) => { this.elementIdElement(result.value.getId(), 'css selector', '.new-element', function(result) { console.log(result.value); }); }); },
'es6 async demo Test': async function(browser) { const elementObject = await browser.findElement('.some-element'); const result = await browser.elementIdElement(elementId.getId(), 'css selector', '.new-element'); console.log(result); } }
See Also
https://nightwatchjs.org/api/elementIdElement.html
method elementIdElements
elementIdElements: ( id: string, using: LocateStrategy, value: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ElementResult[]> ) => void) => Awaitable<this, ElementResult[]>;
Search for multiple elements on the page, starting from the identified element. The located element will be returned as a web element JSON objects.
Example 1
module.exports = { 'demo Test' : function(browser) { browser.findElement('#main', (result) => { browser.elementIdElements(result.value.getId(), 'css selector', 'ul li', function(result) { console.log(result.value) }); }); },
'es6 async demo Test': async function(browser) { const elementObject = await browser.findElement('#main'); const result = await browser.elementIdElements(elementObject.getId(), 'css selector', 'ul li'); console.log(result); } }
See Also
https://nightwatchjs.org/api/elementIdElements.html
method elementIdEquals
elementIdEquals: ( id: string, otherId: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void) => Awaitable<this, boolean>;
Test if two web element IDs refer to the same DOM element.
This command is __deprecated__ and is only available on the [JSON Wire protocol](https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#sessionsessionidelementidequalsother)
Example 1
module.exports = { 'demo Test' : function(browser) { browser.elementIdEquals('', '', function(result) { console.log(result.value) }); } }
See Also
https://nightwatchjs.org/api/elementIdEquals.html
Deprecated
In favour of WebElement.equals(a, b) from Selenium Webdriver.
method elementIdProperty
elementIdProperty: ( webElementId: string, DOMPropertyName: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<any> ) => void) => Awaitable<this, any>;
Retrieve the value of a specified DOM property for the given element. For all the available DOM element properties, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element).
method elements
elements: ( using: LocateStrategy, value: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<ElementResult[]> ) => void) => Awaitable<this, ElementResult[]>;
Search for multiple elements on the page, starting from the document root. The located elements will be returned as web element JSON objects. First argument to be passed is the locator strategy, which is detailed on the [WebDriver docs](https://www.w3.org/TR/webdriver/#locator-strategies).
* The locator strategy can be one of: -
css selector
-link text
-partial link text
-tag name
-xpath
Example 1
module.exports = { 'demo Test' : function(browser) { browser.elements('css selector', 'ul li', function(result) { console.log(result.value) }); },
'es6 async demo Test': async function(browser) { const result = await browser.elements('css selector', 'ul li'); console.log('result value is:', result); },
'page object demo Test': function (browser) { var nightwatch = browser.page.nightwatch(); nightwatch .navigate() .assert.titleContains('Nightwatch.js');
nightwatch.api.elements('@featuresList', function(result) { console.log(result); });
browser.end(); } }
See Also
https://nightwatchjs.org/api/elements.html
interface WebDriverProtocolElementState
interface WebDriverProtocolElementState {}
method elementIdAttribute
elementIdAttribute: ( id: string, attributeName: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string | null> ) => void) => Awaitable<this, string | null>;
Get the value of an element's attribute.
See Also
https://nightwatchjs.org/api/elementIdAttribute.html
method elementIdCssProperty
elementIdCssProperty: ( id: string, cssPropertyName: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<this, string>;
Retrieve the computed value of the given CSS property of the given element.
The CSS property to query should be specified using the CSS property name, not the JavaScript property name (e.g. background-color instead of backgroundColor).
See Also
https://nightwatchjs.org/api/elementIdCssProperty.html
method elementIdDisplayed
elementIdDisplayed: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void) => Awaitable<this, boolean>;
Determine if an element is currently displayed.
See Also
https://nightwatchjs.org/api/elementIdDisplayed.html#apimethod-container
method elementIdEnabled
elementIdEnabled: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void) => Awaitable<this, boolean>;
Determine if an element is currently enabled.
See Also
https://nightwatchjs.org/api/elementIdEnabled.html#apimethod-container
method elementIdName
elementIdName: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<this, string>;
Retrieve the qualified tag name of the given element.
See Also
https://nightwatchjs.org/api/elementIdName.html#apimethod-container
method elementIdSelected
elementIdSelected: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void) => Awaitable<this, boolean>;
Determine if an OPTION element, or an INPUT element of type checkbox or radio button is currently selected.
See Also
https://nightwatchjs.org/api/elementIdSelected.html#apimethod-container
method elementIdSize
elementIdSize: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchSizeAndPosition> ) => void) => Awaitable<this, NightwatchSizeAndPosition>;
Determine an element's size in pixels. The size will be returned as a JSON object with width and height properties.
See Also
https://nightwatchjs.org/api/elementIdSize.html#apimethod-container
Deprecated
In favour of .getElementRect()
method elementIdText
elementIdText: ( id: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<this, string>;
Returns the visible text for the element.
See Also
https://nightwatchjs.org/api/elementIdText.html#apimethod-container
interface WebDriverProtocolMobileRelated
interface WebDriverProtocolMobileRelated {}
method contexts
contexts: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string[]> ) => void) => Awaitable<this, string[]>;
Get a list of the available contexts.
Example 1
browser.contexts();
Used by Appium when testing hybrid mobile web apps. More info here: https://github.com/appium/appium/blob/master/docs/en/advanced-concepts/hybrid.md.
method currentContext
currentContext: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string | null> ) => void) => Awaitable<this, string | null>;
Get current context.
Example 1
browser.currentContext();
method getOrientation
getOrientation: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<'LANDSCAPE' | 'PORTRAIT'> ) => void) => Awaitable<this, 'LANDSCAPE' | 'PORTRAIT'>;
Get the current browser orientation.
Example 1
browser.getOrientation()
method setContext
setContext: ( context: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Sets the context.
Example 1
browser.setContext(context);
method setOrientation
setOrientation: ( orientation: 'LANDSCAPE' | 'PORTRAIT', callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<'LANDSCAPE' | 'PORTRAIT'> ) => void) => Awaitable<this, 'LANDSCAPE' | 'PORTRAIT'>;
Sets the browser orientation.
Example 1
browser.setOrientation(orientation)
interface WebDriverProtocolNavigation
interface WebDriverProtocolNavigation {}
method back
back: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Navigate backwards in the browser history, if possible.
See Also
https://nightwatchjs.org/api/back.html
method forward
forward: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Navigate forwards in the browser history, if possible.
See Also
https://nightwatchjs.org/api/forward.html
method refresh
refresh: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Refresh the current page.
See Also
https://nightwatchjs.org/api/refresh.html
method title
title: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<this, string>;
Get the current page title.
Example 1
this.demoTest = function (browser) { browser.title(function(result) { console.log(result.value); }); }
See Also
https://nightwatchjs.org/api/title.html
method url
url: { ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>; ( url: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Retrieve the URL of the current page or navigate to a new URL.
Example 1
module.exports = { 'demo Test' : function(browser) { browser.url(function(result) { // return the current url console.log(result); }); // // navigate to new url: browser.url('{URL}'); // // // navigate to new url: browser.url('{URL}', function(result) { console.log(result); }); } }
See Also
https://nightwatchjs.org/api/url.html
interface WebDriverProtocolScreenCapture
interface WebDriverProtocolScreenCapture {}
method screenshot
screenshot: { ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>; ( log_screenshot_data: boolean, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): Awaitable<this, string>;};
Take a screenshot of the current page.
Example 1
browser.screenshot(true);
interface WebDriverProtocolSessions
interface WebDriverProtocolSessions {}
method session
session: { ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<Record<string, any>> ) => void ): Awaitable<this, Record<string, any>>; ( actionOrSessionId: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<Record<string, any>> ) => void ): Awaitable<this, Record<string, any>>; ( action: 'get' | 'post' | 'delete' | 'GET' | 'POST' | 'DELETE', sessionId: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<Record<string, any>> ) => void ): Awaitable<this, Record<string, any>>;};
Get info about, delete or create a new session. Defaults to the current session.
Example 1
this.demoTest = function (browser) { browser.session(function(result) { console.log(result.value); }); // browser.session('delete', function(result) { console.log(result.value); }); // browser.session('delete', '12345-abc', function(result) { console.log(result.value); }); }
See Also
https://nightwatchjs.org/api/session.html#apimethod-container
method sessionLog
sessionLog: ( typeString: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchLogEntry[]> ) => void) => Awaitable<this, NightwatchLogEntry[]>;
Gets the text of the log type specified. To find out the available log types, use
.getLogTypes()
.Returns a [log entry JSON object](https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#log-entry-json-object).
Example 1
this.demoTest = function (browser) { browser.sessionLog('client', function(result) { console.log(result.value); }); }
See Also
https://nightwatchjs.org/api/sessionLog.html
method sessionLogTypes
sessionLogTypes: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchLogTypes[]> ) => void) => Awaitable<this, NightwatchLogTypes[]>;
Gets an array of strings for which log types are available. This methods returns the entire WebDriver response, if you are only interested in the logs array, use
.getLogTypes()
instead.Example 1
this.demoTest = function (browser) { browser.sessionLogTypes(function(result) { console.log(result.value); }); }
See Also
https://nightwatchjs.org/api/sessionLogTypes.html
method sessions
sessions: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<Array<Record<string, any>>> ) => void) => Awaitable<this, Array<Record<string, any>>>;
Returns a list of the currently active sessions.
Example 1
this.demoTest = function (browser) { browser.sessions(function(result) { console.log(result.value); }); }
See Also
https://nightwatchjs.org/api/sessions.html
method setNetworkConditions
setNetworkConditions: ( spec: { offline: boolean; latency: number; download_throughput: number; upload_throughput: number; }, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Command to set Chrome network emulation settings.
Example 1
this.demoTest = function() { browser.setNetworkConditions({ offline: false, latency: 50000, download_throughput: 450 * 1024, upload_throughput: 150 * 1024 }); };
See Also
https://nightwatchjs.org/api/setNetworkConditions.html
method status
status: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<NightwatchServerStatusResult> ) => void) => Awaitable<this, NightwatchServerStatusResult>;
Query the server's current status.
See Also
https://nightwatchjs.org/api/status.html
method timeouts
timeouts: { ( typeOfOperation: 'script' | 'implicit' | 'pageLoad', ms: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<{ script: number; implicit: number; pageLoad: number; }> ) => void ): Awaitable<this, { script: number; implicit: number; pageLoad: number }>;};
Configure the amount of time that a particular type of operation can execute for before they are aborted and a |Timeout| error is returned to the client.
Example 1
this.demoTest = function (browser) { browser.timeouts('script', 10000, function(result) { console.log(result); }); }
See Also
https://nightwatchjs.org/api/timeouts.html
method timeoutsAsyncScript
timeoutsAsyncScript: ( ms: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Set the amount of time, in milliseconds, that asynchronous scripts executed by
.executeAsync
are permitted to run before they are aborted and a |Timeout| error is returned to the client.Example 1
this.demoTest = function (browser) { browser.timeoutsAsyncScript(10000, function(result) { console.log(result); }); }
See Also
https://nightwatchjs.org/api/timeoutsAsyncScript.html
method timeoutsImplicitWait
timeoutsImplicitWait: ( ms: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Set the amount of time the driver should wait when searching for elements. If this command is never sent, the driver will default to an implicit wait of 0ms.
Example 1
this.demoTest = function (browser) { browser.timeoutsImplicitWait(10000, function(result) { console.log(result); }); }
See Also
https://nightwatchjs.org/api/timeoutsImplicitWait.html
interface WebDriverProtocolUserActions
interface WebDriverProtocolUserActions {}
method clickAndHold
clickAndHold: { ( selector: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( using: LocateStrategy, selector: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Move to the element and click (without releasing) in the middle of the given element.
Example 1
module.exports = { demoTest() { browser.clickAndHold('#main ul li a.first');
browser.clickAndHold('#main ul li a.first', function(result) { console.log('Click result', result); });
// with explicit locate strategy browser.clickAndHold('css selector', '#main ul li a.first');
// with selector object - see https://nightwatchjs.org/guide#element-properties browser.clickAndHold({ selector: '#main ul li a', index: 1, suppressNotFoundErrors: true });
browser.clickAndHold({ selector: '#main ul li a.first', timeout: 2000 // overwrite the default timeout (in ms) to check if the element is present }); },
demoTestAsync: async function() { const result = await browser.clickAndHold('#main ul li a.first'); console.log('Right click result', result); } }
See Also
https://nightwatchjs.org/api/clickAndHold.html#apimethod-container
method doubleClick
doubleClick: { ( selector: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( using: LocateStrategy, selector: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Move to the element and peforms a double-click in the middle of the element.
Example 1
module.exports = { demoTest() { browser.doubleClick('#main ul li a.first');
browser.doubleClick('#main ul li a.first', function(result) { console.log('double click result', result); });
// with explicit locate strategy browser.doubleClick('css selector', '#main ul li a.first');
// with selector object - see https://nightwatchjs.org/guide#element-properties browser.doubleClick({ selector: '#main ul li a', index: 1, suppressNotFoundErrors: true });
browser.doubleClick({ selector: '#main ul li a.first', timeout: 2000 // overwrite the default timeout (in ms) to check if the element is present }); },
demoTestAsync: async function() { const result = await browser.doubleClick('#main ul li a.first'); console.log('double click result', result); } }
See Also
https://nightwatchjs.org/api/doubleClick.html#apimethod-container
method mouseButtonClick
mouseButtonClick: ( button: 0 | 1 | 2 | 'left' | 'middle' | 'right', callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Click at the current mouse coordinates (set by
.moveTo()
).The button can be (0, 1, 2) or ('left', 'middle', 'right'). It defaults to left mouse button.
See Also
https://nightwatchjs.org/api/mouseButtonClick.html
Deprecated
Please use the new [User Actions API](https://nightwatchjs.org/api/useractions/) instead
method mouseButtonDown
mouseButtonDown: ( button: 0 | 1 | 2 | 'left' | 'middle' | 'right', callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Click and hold the left mouse button (at the coordinates set by the last
moveTo
command). Note that the next mouse-related command that should follow ismouseButtonUp
. Any other mouse command (such as click or another call to buttondown) will yield undefined behaviour.Can be used for implementing drag-and-drop. The button can be (0, 1, 2) or ('left', 'middle', 'right'). It defaults to left mouse button, and if you don't pass in a button but do pass in a callback, it will handle it correctly.
**Since v2.0, this command is deprecated.** It is only available on older JSONWire-based drivers. Please use the new [User Actions API](/api/useractions/).
See Also
https://nightwatchjs.org/api/mouseButtonDown.html
Deprecated
Please use the new [User Actions API](https://nightwatchjs.org/api/useractions/) instead
method mouseButtonUp
mouseButtonUp: ( button: 0 | 1 | 2 | 'left' | 'middle' | 'right', callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Releases the mouse button previously held (where the mouse is currently at). Must be called once for every
mouseButtonDown
command issued.Can be used for implementing drag-and-drop. The button can be (0, 1, 2) or ('left', 'middle', 'right'). It defaults to left mouse button, and if you don't pass in a button but do pass in a callback, it will handle it correctly.
**Since v2.0, this command is deprecated.** It is only available on older JSONWire-based drivers. Please use the new [User Actions API](/api/useractions/).
See Also
https://nightwatchjs.org/api/mouseButtonUp.html
Deprecated
Please use the new [User Actions API](https://nightwatchjs.org/api/useractions/) instead
method moveTo
moveTo: { ( elementId: string | null, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( xoffset: number, yoffset: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( elementId: string, xoffset: number, yoffset: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Move the mouse by an offset of the specified [Web Element ID](https://www.w3.org/TR/webdriver1/#dfn-web-elements) or relative to the current mouse cursor, if no element is specified. If an element is provided but no offset, the mouse will be moved to the center of the element.
If an element is provided but no offset, the mouse will be moved to the center of the element. If the element is not visible, it will be scrolled into view.
Example 1
this.demoTest = function (browser) { browser.moveTo(null, 110, 100); };
See Also
https://nightwatchjs.org/api/moveTo.html#apimethod-container
method releaseMouseButton
releaseMouseButton: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Release the depressed left mouse button at the current mouse coordinates (set by
.moveTo()
).
method rightClick
rightClick: { ( selector: Definition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>; ( using: LocateStrategy, selector: any, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): Awaitable<this, null>;};
Simulates a context-click(right click) event on the given DOM element. The element is scrolled into view if it is not already pointer-interactable. See the WebDriver specification for element [interactability](https://www.w3.org/TR/webdriver/#element-interactability).
Example 1
module.exports = { demoTest() { browser.rightClick('#main ul li a.first');
browser.rightClick('#main ul li a.first', function(result) { console.log('Click result', result); });
// with explicit locate strategy browser.rightClick('css selector', '#main ul li a.first');
// with selector object - see https://nightwatchjs.org/guide#element-properties browser.rightClick({ selector: '#main ul li a', index: 1, suppressNotFoundErrors: true });
browser.rightClick({ selector: '#main ul li a.first', timeout: 2000 // overwrite the default timeout (in ms) to check if the element is present }); },
demoTestAsync: async function() { const result = await browser.rightClick('#main ul li a.first'); console.log('Right click result', result); } }
See Also
https://nightwatchjs.org/api/rightClick.html#apimethod-container
interface WebDriverProtocolUserPrompts
interface WebDriverProtocolUserPrompts {}
method acceptAlert
acceptAlert: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Accepts the currently displayed alert dialog. Usually, this is equivalent to clicking on the 'OK' button in the dialog.
Example 1
browser.acceptAlert()
See Also
https://nightwatchjs.org/api/acceptAlert.html#apimethod-container
method dismissAlert
dismissAlert: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Dismisses the currently displayed alert dialog. For confirm() and prompt() dialogs, this is equivalent to clicking the 'Cancel' button.
For alert() dialogs, this is equivalent to clicking the 'OK' button.
Example 1
browser.dismissAlert();
See Also
https://nightwatchjs.org/api/dismissAlert.html#apimethod-container
method getAlertText
getAlertText: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => Awaitable<this, string>;
Gets the text of the currently displayed JavaScript alert(), confirm(), or prompt() dialog.
Example 1
browser.getAlertText();
See Also
https://nightwatchjs.org/api/getAlertText.html#apimethod-container
method registerBasicAuth
registerBasicAuth: ( username: string, password: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Automate the input of basic auth credentials whenever they arise.
Example 1
this.demoTest = function (browser) { browser .registerBasicAuth('test-username', 'test-password') .navigateTo('http://browserspy.dk/password-ok.php'); };
See Also
https://nightwatchjs.org/api/registerBasicAuth.html#apimethod-container
method setAlertText
setAlertText: ( value: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => Awaitable<this, null>;
Sends keystrokes to a JavaScript prompt() dialog.
Example 1
browser.setAlertText('randomalert');
See Also
https://nightwatchjs.org/api/setAlertText.html#apimethod-container
interface WindowPosition
interface WindowPosition {}
interface WindowSize
interface WindowSize {}
Type Aliases
type Awaitable
type Awaitable<T, V> = Omit<T, 'then'> & PromiseLike<V>;
type Definition
type Definition = string | ElementProperties | Element | By | RelativeBy;
type EnhancedPageObject
type EnhancedPageObject< Commands = {}, Elements = {}, Sections extends EnhancedPageObjectSections = {}> = SharedCommands & NightwatchCustomCommands & Commands & { /** * A map of Element objects (see [Enhanced Element Instances](https://github.com/nightwatchjs/nightwatch/wiki/Page-Object-API#enhanced-element-instances)) used by element selectors. */ elements: { [name: string]: EnhancedElementInstance< EnhancedPageObject<Commands, Elements, Sections> >; };
section: Sections;
/** * The name of the page object as defined by its module name (not including the extension). * This is the same name used to access the `page` object factory from the page reference in the command API. */ name: string;
/** * This command is an alias to url and also a convenience method because when called without any arguments * it performs a call to .url() with passing the value of `url` property on the page object. * Uses `url` protocol command. */ navigate( url?: string, callback?: () => void ): EnhancedPageObject<Commands, Elements, Sections>;
// TODO: `props` property missing. url: string | undefined;
/** * Nightwatch API. */ api: NightwatchAPI;
/** * Nightwatch Client. */ client: NightwatchClient;
assert: Assert; verify: Assert; // TODO: revisit this, some additional properties/methods are also available on // expect when using VSCode Debugger, like active, attribute, etc. expect: Expect; };
#### [Enhanced Page Object Instances](https://github.com/nightwatchjs/nightwatch/wiki/Page-Object-API#enhanced-page-object-instances) Page object module definitions are used to define page object instances when their respective factory functions within the page reference of the standard command API is called.
var myPageObject = browser.page.MyPage(); // defined in MyPage.js moduleEvery time a factory function like MyPage above is called, a new instance of the page object is instantiated.
type EnhancedSectionInstance
type EnhancedSectionInstance< Commands = {}, Elements = {}, Sections extends EnhancedPageObjectSections = {}> = EnhancedPageObject<Commands, Elements, Sections>;
type ExtendDescribeThis
type ExtendDescribeThis<T> = DescribeInstance & { [P in keyof T]?: T[P] };
type GlobalNightwatchTestHook
type GlobalNightwatchTestHook = (done: (err?: any) => void) => void;
type GlobalNightwatchTestHookEach
type GlobalNightwatchTestHookEach = ( browser: NightwatchBrowser, done: (err?: any) => void) => void;
type LocateStrategy
type LocateStrategy = | 'class name' | 'css selector' | 'id' | 'name' | 'link text' | 'partial link text' | 'tag name' | 'xpath';
type NightwatchAssert
type NightwatchAssert = ( passed: boolean, receivedValue?: any, expectedValue?: any, message?: string, abortOnFailure?: boolean, originalStackTrace?: string) => void;
Performs an assertion
type NightwatchCallbackResult
type NightwatchCallbackResult<T> = | NightwatchTypedCallbackResult<T> | NightwatchCallbackResultError;
type NightwatchLogTypes
type NightwatchLogTypes = 'client' | 'driver' | 'browser' | 'server' | 'performance';
type NightwatchPage
type NightwatchPage = { [name: string]: () => EnhancedPageObject<any, any, any>;} & { [name: string]: NightwatchPage;};
type NightwatchSizeAndPosition
type NightwatchSizeAndPosition = WindowSizeAndPosition;
type NightwatchTest
type NightwatchTest = (browser?: NightwatchBrowser) => void;
type NightwatchTestHook
type NightwatchTestHook = GlobalNightwatchTestHookEach | GlobalNightwatchTestHook;
type NightwatchTests
type NightwatchTests = NightwatchTestFunctions | NightwatchTestHooks;
type WindowSizeAndPosition
type WindowSizeAndPosition = WindowPosition & WindowSize;
type WindowType
type WindowType = 'tab' | 'window';
Namespaces
namespace global
namespace global {}
variable after
const after: NightwatchBddTestHook;
variable afterEach
const afterEach: NightwatchBddTestHook;
variable before
const before: NightwatchBddTestHook;
variable beforeEach
const beforeEach: NightwatchBddTestHook;
variable context
const context: SuiteFunction;
variable describe
const describe: SuiteFunction;
variable it
const it: TestFunction;
variable specify
const specify: TestFunction;
variable test
const test: TestFunction;
variable xcontext
const xcontext: PendingSuiteFunction;
variable xdescribe
const xdescribe: PendingSuiteFunction;
variable xit
const xit: PendingTestFunction;
variable xspecify
const xspecify: PendingTestFunction;
Package Files (2)
Dependencies (4)
Dev Dependencies (0)
No dev dependencies.
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@types/nightwatch
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@types/nightwatch)
- HTML<a href="https://www.jsdocs.io/package/@types/nightwatch"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 13811 ms. - Missing or incorrect documentation? Open an issue for this package.