@types/nightwatch
- Version 2.0.7
- Published
- 172 kB
- 1 dependency
- 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
- closeWindow()
- deleteCookie()
- deleteCookies()
- end()
- getCookie()
- getCookies()
- getLog()
- getLogTypes()
- getTitle()
- getWindowPosition()
- getWindowRect()
- getWindowSize()
- init()
- injectScript()
- isLogAvailable()
- maximizeWindow()
- pageSource()
- pause()
- perform()
- resizeWindow()
- saveScreenshot()
- setCookie()
- setWindowPosition()
- setWindowRect()
- setWindowSize()
- switchWindow()
- urlHash()
- useCss()
- useXpath()
ElementCommands
- clearValue()
- click()
- dragAndDrop()
- findElement()
- findElements()
- getAccessibleName()
- getAriaRole()
- getAttribute()
- getCssProperty()
- getElementProperty()
- getElementRect()
- getElementSize()
- getLocation()
- getLocationInView()
- getTagName()
- getText()
- getValue()
- isEnabled()
- isSelected()
- isVisible()
- moveToElement()
- sendKeys
- setAttribute()
- setPassword()
- setValue()
- submitForm()
- takeElementScreenshot()
- uploadFile()
- waitForElementNotPresent()
- waitForElementNotVisible()
- waitForElementPresent()
- waitForElementVisible()
NightwatchCommonAssertions
- attributeContains()
- attributeEquals()
- containsText()
- cssClassPresent()
- cssProperty()
- deepEqual()
- deepStrictEqual()
- doesNotThrow()
- domPropertyContains()
- domPropertyEquals()
- elementPresent()
- enabled()
- equal()
- fail()
- ifError()
- NightwatchAssertionsError
- notDeepEqual()
- notDeepStrictEqual()
- notEqual()
- notStrictEqual()
- ok()
- selected()
- strictEqual()
- throws()
- title()
- titleContains()
- titleEquals()
- urlContains()
- urlEquals()
- value()
- valueContains()
- 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
- 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_prefix
- selenium
- skip_testcases_on_fail
- skipgroup
- skiptags
- src_folders
- start_process
- sync_test_names
- test_runner
- test_settings
- test_workers
- unit_testing_mode
- use_xpath
- webdriver
Type Aliases
Variables
variable after
const after: GlobalNightwatchTestHook;
variable afterEach
const afterEach: GlobalNightwatchTestHookEach;
variable before
const before: GlobalNightwatchTestHook;
variable beforeEach
const beforeEach: GlobalNightwatchTestHookEach;
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;
Functions
function element
element: ( locator: string | ElementProperties | By | WebElement, options?: any) => WebElement;
Classes
class DescribeInstance
class DescribeInstance {}
property '[attributes]'
'[attributes]': {};
property '[client]'
'[client]': NightwatchClient;
property '[instance]'
'[instance]': any;
method argv
argv: () => any;
method define
define: (name: any, value: any) => any;
method desiredCapabilities
desiredCapabilities: () => NightwatchDesiredCapabilities;
method disabled
disabled: () => boolean;
method endSessionOnFail
endSessionOnFail: () => boolean;
method globals
globals: () => NightwatchGlobals;
method name
name: () => string;
method page
page: () => any;
method retries
retries: (n: any) => void;
method retryInterval
retryInterval: (value: number) => void;
method settings
settings: () => NightwatchOptions;
method skipTestcasesOnFail
skipTestcasesOnFail: () => boolean;
method suiteRetries
suiteRetries: (n: any) => void;
method tags
tags: () => string | string[];
method timeout
timeout: (value: number) => void;
method unitTest
unitTest: () => boolean;
method waitForRetryInterval
waitForRetryInterval: (value: number) => number | void;
method waitForTimeout
waitForTimeout: (value: number) => number | void;
Interfaces
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 ClientCommands
interface ClientCommands {}
method closeWindow
closeWindow: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => this;
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
this.demoTest = function () { browser.closeWindow(); };
See Also
window
method deleteCookie
deleteCookie: ( cookieName: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => this;
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
cookie
method deleteCookies
deleteCookies: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => this;
Delete all cookies visible to the current page.
Example 1
this.demoTest = function() { browser.deleteCookies(function() { // do something more in here }); }
See Also
cookie
method end
end: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void) => this;
Ends the session. Uses session protocol command.
Example 1
this.demoTest = function () { browser.end(); };
See Also
session
method getCookie
getCookie: ( name: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<Cookie> ) => void) => this;
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
cookie
method getCookies
getCookies: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<Cookie[]> ) => void) => this;
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
cookie
method getLog
getLog: ( typestring: string, callback?: (this: NightwatchAPI, log: NightwatchLogEntry[]) => void) => this;
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
getLogTypes
method getLogTypes
getLogTypes: ( callback?: ( this: NightwatchAPI, result: Array<'client' | 'driver' | 'browser' | 'server' | 'performance'> ) => void) => this;
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
sessionLogTypes
method getTitle
getTitle: (callback?: (this: NightwatchAPI, result?: string) => void) => this;
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
title
method getWindowPosition
getWindowPosition: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<{ x: number; y: number }> ) => void) => this;
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
windowRect
method getWindowRect
getWindowRect: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<{ x: number; y: number; width: number; height: number; }> ) => void) => this;
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
windowRect
method getWindowSize
getWindowSize: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<{ x: number; y: number; width: number; height: number; }> ) => void) => this;
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); } }
method init
init: (url?: string) => this;
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
url
method injectScript
injectScript: ( scriptUrl: string, id?: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void) => this;
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. }); };
method isLogAvailable
isLogAvailable: ( typeString: string, callback?: (this: NightwatchAPI, result: boolean) => void) => this;
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
getLogTypes
method maximizeWindow
maximizeWindow: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void) => this;
Maximizes the current window.
Example 1
this.demoTest = function () { browser.maximizeWindow(); };
See Also
windowMaximize
method pageSource
pageSource: ( callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => this;
Returns the page source. Uses pageSource protocol command.
Example 1
this.demoTest = function (browser) { browser.pageSource(function(pageSource) { console.log(pageSource); }); };
See Also
pageSource
method pause
pause: (ms?: number, callback?: (this: NightwatchAPI) => void) => this;
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(); };
method perform
perform: ( callback: | (() => undefined | Promise<any>) | ((done: () => void) => void) | ((client: NightwatchAPI, done: () => void) => void)) => this;
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
this.demoTest = function () { var elementValue; 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) }) // // asynchronous completion .perform(function(done) { console.log('elementValue', elementValue); // potentially other async stuff going on // on finished, call the done callback done(); }) // // asynchronous completion including api (client) .perform(function(done) { console.log('elementValue', elementValue); // similar to before, but now with client // potentially other async stuff going on // on finished, call the done callback done(); }); };
method resizeWindow
resizeWindow: ( width: number, height: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void) => this;
Resizes the current window.
Example 1
this.demoTest = function () { browser.resizeWindow(1000, 800); };
See Also
windowSize
method saveScreenshot
saveScreenshot: ( fileName: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void) => this;
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
screenshot
method setCookie
setCookie: ( cookie: Cookie, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void) => this;
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
cookie
method setWindowPosition
setWindowPosition: ( offsetX: number, offsetY: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void) => this;
Sets the current window position.
Example 1
this.demoTest = function () { browser.setWindowPosition(0, 0); };
See Also
windowPosition
method setWindowRect
setWindowRect: ( options: windowSizeAndPosition, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void) => this;
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
windowRect
method setWindowSize
setWindowSize: ( width: number, height: number, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void) => this;
Sets the current window position.
Example 1
this.demoTest = function () { browser.setWindowPosition(0, 0); };
See Also
windowSize
method switchWindow
switchWindow: ( handleOrName: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void) => this;
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) { var handle = result.value[0]; browser.switchWindow(handle); }); };
this.demoTestAsync = async function () { const result = browser.windowHandles(); var handle = result.value[0]; browser.switchWindow(handle); };
See Also
window
method urlHash
urlHash: ( hash: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void) => this;
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
url
method useCss
useCss: (callback?: (this: NightwatchAPI) => void) => this;
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'); };
method useXpath
useXpath: (callback?: (this: NightwatchAPI) => void) => this;
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']"); };
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;
property globals
globals?: any;
property headless
headless?: boolean;
property output
output?: boolean;
property parallel
parallel?: boolean;
property reporter
reporter?: null;
property silent
silent?: boolean;
property timeout
timeout?: number;
property useAsync
useAsync?: boolean;
interface ElementCommands
interface ElementCommands {}
property sendKeys
sendKeys: SharedCommands['setValue'];
Alias for
setValue
.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.
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
setValue
method clearValue
clearValue: { ( selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): this;};
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
module.exports = { demoTest() { 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
elementIdClear
method click
click: { ( selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<null> ) => void ): this;};
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
elementIdClick
method dragAndDrop
dragAndDrop: { ( selector: string | ElementProperties, destination: NightwatchElement | { x: number; y: number }, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, destination: NightwatchElement | { x: number; y: number }, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void ): this;};
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()); } }
method findElement
findElement: { ( selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<{ value: WebElement; status: number; WebdriverElementId: WebElement; }> ) => void ): WebElementPromise; ( using: LocateStrategy, selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<{ value: WebElement; status: number; WebdriverElementId: WebElement; }> ) => void ): WebElementPromise;};
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()); },
method findElements
findElements: { ( selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<{ value: WebElement[]; status: number; WebdriverElementId: WebElement; }> ) => void ): WebElement[]; ( using: LocateStrategy, selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<{ value: WebElement[]; status: number; WebdriverElementId: WebElement; }> ) => void ): WebElement[];};
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())); },
method getAccessibleName
getAccessibleName: { ( selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): this;};
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); } }
method getAriaRole
getAriaRole: { ( selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): this;};
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); } }
method getAttribute
getAttribute: { ( selector: string | ElementProperties, attribute: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string | null> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, attribute: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): this;};
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
elementIdAttribute
method getCssProperty
getCssProperty: { ( selector: string | ElementProperties, cssProperty: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, cssProperty: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): this;};
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
elementIdCssProperty
method getElementProperty
getElementProperty: { ( selector: string | ElementProperties, property: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<any> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, property: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<any> ) => void ): this;};
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); } }
method getElementRect
getElementRect: { ( selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<{ height: number; width: number; x: number; y: number; }> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<{ height: number; width: number; x: number; y: number; }> ) => void ): this;};
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); } }
method getElementSize
getElementSize: { ( selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<{ width: number; height: number; x: number; y: number; }> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<{ width: number; height: number; x: number; y: number; }> ) => void ): this;};
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
elementIdSize
method getLocation
getLocation: { ( selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<{ x: number; y: number; width: number; height: number; }> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<{ x: number; y: number; width: number; height: number; }> ) => void ): this;};
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
elementIdLocation
method getLocationInView
getLocationInView: { ( selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<{ x: number; y: number }> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<{ x: number; y: number }> ) => void ): this;};
Determine an element's location on the screen once it has been scrolled into view. Uses
elementIdLocationInView
protocol command.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
elementIdLocationInView
method getTagName
getTagName: { ( selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): this;};
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
elementIdName
method getText
getText: { ( selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): this;};
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
elementIdText
method getValue
getValue: { ( selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => void ): this;};
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
elementIdValue
method isEnabled
isEnabled: { ( selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void ): this;};
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); } }
method isSelected
isSelected: { ( selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void ): this;};
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); } }
method isVisible
isVisible: { ( selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<boolean> ) => void ): this;};
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
elementIdDisplayed
method moveToElement
moveToElement: { ( selector: string | ElementProperties, xoffset: number, yoffset: number, duration: number, origin: { pointer: number; viewport: number }, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, xoffset: number, yoffset: number, duration: number, origin: { pointer: number; viewport: number }, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void ): this;};
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
moveTo
method setAttribute
setAttribute: { ( selector: string | ElementProperties, attribute: string, value: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, attribute: string, value: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void ): this;};
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'); } }
method setPassword
setPassword: { ( selector: string | ElementProperties, inputValue: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, inputValue: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void ): this;};
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: string | ElementProperties, inputValue: string | string[], callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, inputValue: string | string[], callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void ): this;};
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.
setValue does 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.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
elementIdValue
method submitForm
submitForm: { ( selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void ): this;};
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
submit
method takeElementScreenshot
takeElementScreenshot: { ( selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => string ): this; ( using: LocateStrategy, selector: string | ElementProperties, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<string> ) => string ): this;};
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'); } }
method uploadFile
uploadFile: { ( selector: string | ElementProperties, filePath: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void ): this; ( using: LocateStrategy, selector: string | ElementProperties, filePath: string, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void ): this;};
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'); };
method waitForElementNotPresent
waitForElementNotPresent: { ( selector: string | ElementProperties, time?: number, poll?: number, abortOnFailure?: boolean, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void, message?: string ): this; ( using: LocateStrategy, selector: string | ElementProperties, time?: number, poll?: number, abortOnFailure?: boolean, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void, message?: string ): this;};
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).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
waitForElementPresent v0.4.0
method waitForElementNotVisible
waitForElementNotVisible: { ( selector: string | ElementProperties, time?: number, poll?: number, abortOnFailure?: boolean, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void, message?: string ): this; ( using: LocateStrategy, selector: string | ElementProperties, time?: number, poll?: number, abortOnFailure?: boolean, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void, message?: string ): this;};
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).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
waitForElementVisible
method waitForElementPresent
waitForElementPresent: { ( selector: string | ElementProperties, time?: number, poll?: number, abortOnFailure?: boolean, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void, message?: string ): this; ( using: LocateStrategy, selector: string | ElementProperties, time?: number, poll?: number, abortOnFailure?: boolean, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void, message?: string ): this;};
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).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); }); } }
method waitForElementVisible
waitForElementVisible: { ( selector: string | ElementProperties, time?: number, poll?: number, abortOnFailure?: boolean, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void, message?: string ): this; ( using: LocateStrategy, selector: string | ElementProperties, time?: number, poll?: number, abortOnFailure?: boolean, callback?: ( this: NightwatchAPI, result: NightwatchCallbackResult<void> ) => void, message?: string ): this;};
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).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'); };
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 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 Expect
interface Expect extends NightwatchLanguageChains, NightwatchBrowser {}
property enabled
enabled: this;
Property that checks if an element is currently enabled.
property not
not: this;
Negates any of assertions following in the chain.
property present
present: this;
Property that checks if an element is present in the DOM.
property selected
selected: this;
Property that checks if an OPTION element, or an INPUT element of type checkbox or radio button is currently selected.
property text
text: this;
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: this;
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: this;
Property that asserts the visibility of a specified element.
method a
a: (value: string, message?: string) => this;
Checks if the type (i.e. tag name) of a specified element is of an expected value.
method after
after: (value: number) => this;
method an
an: (value: string, message?: string) => this;
method attribute
attribute: (name: string, message?: string) => this;
Checks if a given attribute of an element exists and optionally if it has the expected value.
method before
before: (value: number) => this;
These methods perform the same thing which is essentially retrying the assertion for the given amount of time (in milliseconds). before or after can be chained to any assertion and thus adding retry capability. You can change the polling interval by defining a waitForConditionPollInterval property (in milliseconds) as a global property in your nightwatch.json or in your external globals file. Similarly, a default timeout can be specified as a global waitForConditionTimeout property (in milliseconds).
method contain
contain: (value: string) => this;
method contains
contains: (value: string) => this;
method css
css: (property: string, message?: string) => this;
Checks a given css property of an element exists and optionally if it has the expected value.
method element
element: (property: any) => this;
Returns the DOM Element
method endsWith
endsWith: (value: string) => this;
method endWith
endWith: (value: string) => this;
method equal
equal: (value: string) => this;
These methods will perform assertions on the specified target on the current element. The targets can be an attribute value, the element's inner text and a css property.
method equals
equals: (value: string) => this;
method match
match: (value: string | RegExp) => this;
method section
section: (property: string) => this;
method startsWith
startsWith: (value: string) => this;
method startWith
startWith: (value: string) => this;
interface Level
interface Level {}
interface Nightwatch
interface Nightwatch {}
property api
api: NightwatchAPI;
property assert
assert: NightwatchAssertions;
property expect
expect: Expect;
property verify
verify: NightwatchAssertions;
method cli
cli: (callback: any) => this;
method client
client: (settings: NightwatchOptions, reporter?: any, argv?: {}) => this;
method cliRunner
cliRunner: (argv?: {}) => this;
method createClient
createClient: ({ headless, silent, output, useAsync, env, timeout, parallel, reporter, browserName, globals, devtools, debug, enable_global_apis, config,}: CreateClientParams) => this;
method initClient
initClient: (opts: any) => this;
method runner
runner: (argv?: {}, done?: () => void, settings?: {}) => this;
method runTests
runTests: (testSource: string | string[], settings?: any, ...args: any[]) => any;
interface NightwatchAPI
interface NightwatchAPI extends SharedCommands, WebDriverProtocol, NightwatchCustomCommands {}
property assert
assert: NightwatchAssertions;
property baseURL
baseURL: string;
property currentTest
currentTest: NightwatchTestSuite;
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: NightwatchTestOptions;
property page
page: NightwatchPage & NightwatchCustomPageObjects;
property sessionId
sessionId: string;
SessionId of the session used by the Nightwatch api.
property verify
verify: NightwatchAssertions;
method setSessionId
setSessionId: (sessionId: string) => this;
Override the sessionId used by Nightwatch client with another session id.
interface NightwatchAssertion
interface NightwatchAssertion<T, U = any> {}
Abstract assertion class that will subclass all defined assertions
All assertions must implement the following api:
-
Parameter expected
Parameter message
Parameter pass
Parameter value
Parameter command
Parameter
{function} - Optional failure
property api
api: NightwatchAPI;
property client
client: NightwatchClient;
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: this;
Negates any of assertions following in the chain.
interface NightwatchAssertionsError
interface NightwatchAssertionsError {}
interface NightwatchBrowser
interface NightwatchBrowser extends NightwatchAPI, NightwatchComponentTestingCommands, NightwatchCustomCommands {}
interface NightwatchCallbackResultError
interface NightwatchCallbackResultError {}
interface NightwatchClient
interface NightwatchClient {}
property api
api: NightwatchAPI;
property locateStrategy
locateStrategy: LocateStrategy;
property options
options: NightwatchOptions;
property sessionID
sessionID: string;
property settings
settings: NightwatchOptions;
interface NightwatchCommonAssertions
interface NightwatchCommonAssertions {}
property NightwatchAssertionsError
NightwatchAssertionsError: NightwatchAssertionsError;
method attributeContains
attributeContains: ( selector: string | ElementProperties, attribute: string, expected: string, message?: string) => NightwatchAPI;
Checks if the given attribute of an element contains the expected value.
this.demoTest = function (client) {browser.assert.attributeContains('#someElement', 'href', 'google.com');};
method attributeEquals
attributeEquals: ( selector: string | ElementProperties, attribute: string, expected: string, message?: string) => NightwatchAPI;
Checks if the given attribute of an element has the expected value.
this.demoTest = function (client) {browser.assert.attributeEquals('body', 'data-attr', 'some value');};
method containsText
containsText: ( selector: string | ElementProperties, expectedText: string, message?: string) => NightwatchAPI;
Checks if the given element contains the specified text.
this.demoTest = function (client) {browser.assert.containsText('#main', 'The Night Watch');};
method cssClassPresent
cssClassPresent: ( selector: string | ElementProperties, className: string, message?: string) => NightwatchAPI;
Checks if the given element has the specified CSS class.
this.demoTest = function (client) {browser.assert.cssClassPresent('#main', 'container');};
method cssProperty
cssProperty: ( selector: string | ElementProperties, cssProperty: string, expected: string | number, msg?: string) => NightwatchAPI;
Checks if the specified css property of a given element has the expected value.
this.demoTest = function (client) {browser.assert.cssProperty('#main', 'display', 'block');};
method deepEqual
deepEqual: (value: any, expected: any, message?: string) => NightwatchAPI;
method deepStrictEqual
deepStrictEqual: (value: any, expected: any, message?: string) => NightwatchAPI;
method doesNotThrow
doesNotThrow: (value: any, expected: any, message?: string) => NightwatchAPI;
method domPropertyContains
domPropertyContains: ( selector: string | ElementProperties, domProperty: string, expected: string | number, msg?: string) => NightwatchAPI;
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: string | ElementProperties, domProperty: string, expected: string | number, msg?: string) => NightwatchAPI;
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 elementPresent
elementPresent: ( selector: string | ElementProperties, msg?: string) => NightwatchAPI;
Checks if the given element exists in the DOM.
this.demoTest = function (client) {browser.assert.elementPresent("#main");};
method enabled
enabled: ( selector: string | ElementProperties, message?: string) => NightwatchAPI;
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 equal
equal: (value: any, expected: any, message?: string) => NightwatchAPI;
method fail
fail: ( actual?: any, expected?: any, message?: string, operator?: string) => NightwatchAPI;
method ifError
ifError: (value: any, message?: string) => NightwatchAPI;
method notDeepEqual
notDeepEqual: (actual: any, expected: any, message?: string) => NightwatchAPI;
method notDeepStrictEqual
notDeepStrictEqual: (value: any, message?: string) => NightwatchAPI;
method notEqual
notEqual: (actual: any, expected: any, message?: string) => NightwatchAPI;
method notStrictEqual
notStrictEqual: (value: any, expected: any, message?: string) => NightwatchAPI;
method ok
ok: (actual: boolean, message?: string) => NightwatchAPI;
method selected
selected: ( selector: string | ElementProperties, message?: string) => NightwatchAPI;
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 strictEqual
strictEqual: (value: any, expected: any, message?: string) => NightwatchAPI;
method throws
throws: (fn: () => void, message?: string) => NightwatchAPI;
method title
title: (expected: string, message?: string) => NightwatchAPI;
Checks if the page title equals the given value.
See Also
assert.titleEquals()
this.demoTest = function (client) {browser.assert.title("Nightwatch.js");};
Deprecated
in Nightwatch 2.0 and will be removed from future versions.
method titleContains
titleContains: (expected: string, message?: string) => NightwatchAPI;
Checks if the page title equals the given value.
this.demoTest = function (client) {browser.assert.title("Nightwatch.js");};
method titleEquals
titleEquals: (expected: string, message?: string) => NightwatchAPI;
Checks if the page title equals the given value. 2.0
this.demoTest = function (client) {browser.assert.titleEquals("Nightwatch.js");};
method urlContains
urlContains: (expectedText: string, message?: string) => NightwatchAPI;
Checks if the current URL contains the given value.
this.demoTest = function (client) {browser.assert.urlContains('google');};
method urlEquals
urlEquals: (expected: string, message?: string) => NightwatchAPI;
Checks if the current url equals the given value.
this.demoTest = function (client) {browser.assert.urlEquals('https://www.google.com');};
method value
value: ( selector: string | ElementProperties, expectedText: string, message?: string) => NightwatchAPI;
Checks if the given form element's value equals the expected value.
this.demoTest = function (client) {browser.assert.value("form.login input[type=text]", "username");};
method valueContains
valueContains: ( selector: string | ElementProperties, expectedText: string, message?: string) => NightwatchAPI;
Checks if the given form element's value contains the expected value.
this.demoTest = function (client) {browser.assert.valueContains("form.login input[type=text]", "username");};
method visible
visible: ( selector: string | ElementProperties, message?: string) => NightwatchAPI;
Checks if the given element is visible on the page.
this.demoTest = function (client) {browser.assert.visible(".should_be_visible");};
interface NightwatchComponentTestingCommands
interface NightwatchComponentTestingCommands {}
method importScript
importScript: ( scriptPath: string, options: { scriptType: string; componentTyp: string }, callback: () => void) => this;
method launchComponentRenderer
launchComponentRenderer: () => this;
method mountReactComponent
mountReactComponent: ( componentPath: string, props?: string | (() => void), callback?: () => void) => this;
method mountVueComponent
mountVueComponent: ( componentPath: string, options?: any, callback?: () => void) => this;
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 | undefined;
The name of the browser being used; should be one of {android|chrome|firefox|htmlunit|internet explorer|iPhone|iPad|opera|safari}.
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 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 NightwatchLanguageChains
interface NightwatchLanguageChains {}
interface NightwatchLogEntry
interface NightwatchLogEntry {}
property level
level: | 'ALL' | 'DEBUG' | 'FINE' | 'FINER' | 'FINEST' | 'INFO' | 'OFF' | 'SEVERE' | 'WARNING' | Level | number;
Severity level
property message
message: string;
The log entry message.
property opt_timestamp
opt_timestamp: number;
The time stamp of log entry in seconds.
property opt_type
opt_type?: string;
The log type, if known.
interface NightwatchOptions
interface NightwatchOptions {}
property backwards_compatibility_mode
backwards_compatibility_mode?: boolean;
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;
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 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