### Extra Setup for Manual Session Start Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/writing-tests/using-cucumberjs.md Use an extra setup file to manually launch the browser and manage the WebDriver session before tests run. ```javascript const { Before } = require('@cucumber/cucumber'); Before(async function(testCase) { if (!this.client) { console.error('Nightwatch instance was not created.'); return; } this.client.updateCapabilities({ testCap: 'testing' }); this.browser = await this.client.launchBrowser(); }); ``` -------------------------------- ### Extra Setup File for Manual Session Start Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/third-party-runners/cucumberjs-nightwatch-integration.md Example of an extra setup file for Cucumber.js that manually launches the WebDriver session and sets the browser instance. ```javascript const {Before} = require('@cucumber/cucumber');
Before(async function(testCase) { if (!this.client) { console.error('Nightwatch instance was not created.');
return; }
this.client.updateCapabilities({ testCap: 'testing' });
this.browser = await this.client.launchBrowser(); }); ``` -------------------------------- ### Setting up a Mock Server Route Definition Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/writing-tests/api-testing.md This example shows how to use the `mockServer.setup()` method to define a GET route for '/api/v1/schemas'. It logs a message when the route is called and returns a JSON array of schema objects. ```javascript await mockServer.setup((app) => { app.get('/api/v1/schemas', function (req, res) { console.log('GET /api/v1/schemas called'); res.status(200).json([ { id: 'test-schema-id1' }, { id: 'test-schema-id2' } ]); }) }); ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/README.md Clone the nightwatch-docs repository and install its dependencies to get started. ```bash git clone https://github.com/nightwatchjs/nightwatch-docs.git npm install ``` -------------------------------- ### Create New Project and Install Dependencies Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/reporters/use-junit-reporter.md Steps to set up a new project and install Nightwatch and chromedriver. ```bash mkdir ./test-project && cd ./test-project ``` ```bash npm i nightwatch chromedriver ``` -------------------------------- ### Initialize New Nightwatch Project for Mobile App Testing Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/mobile-app-testing/installation.md Use this command to start a new Nightwatch project and select 'Mobile app testing' during the setup process. ```bash npm init nightwatch ``` -------------------------------- ### Example Nightwatch Configuration File Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/configuration/nightwatch-configuration-file.md This is a basic example of a `nightwatch.conf.js` file. It specifies the source folders for tests, configures the webdriver to start a process for geckodriver, and sets default desired capabilities for Firefox. ```javascript module.exports = { // An array of folders (excluding subfolders) where your tests are located; // if this is not specified, the test source must be passed as the second argument to the test runner. src_folders: [], webdriver: { start_process: true, port: 4444, server_path: require('geckodriver').path, cli_args: [ // very verbose geckodriver logs // '-vv' ] }, test_settings: { default: { launch_url: 'https://nightwatchjs.org', desiredCapabilities : { browserName : 'firefox' } } } }; ``` -------------------------------- ### Open Website in Browser on Start Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/README.md Start the development server and automatically open the website in a specified browser. ```bash npm start -- --open [chrome|firefox|edge|safari] ``` -------------------------------- ### Setup iOS Mobile Helper Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/mobile-app-testing/installation.md Initializes the mobile helper for iOS setup within the Nightwatch project directory. ```bash npx @nightwatch/mobile-helper ios --setup ``` -------------------------------- ### Start Activity Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/mobile-app-testing/commands.md Starts a new activity within the application with specified options. ```APIDOC ## Start Activity ### Description Starts a new Android Activity. ### Method `app.appium.startActivity(options)` ### Parameters - **options** (object) - Required - A JSON object with activity details. - **appPackage** (string) - Required - Name of the package. - **appActivity** (string) - Required - Name of the activity. - **appWaitPackage** (string) - Optional - Automation will begin after this package starts. - **appWaitActivity** (string) - Optional - Automation will begin after this activity starts. - **intentAction** (string) - Optional - Intent action to start the activity. - **intentCategory** (string) - Optional - Intent category to start the activity. - **intentFlags** (string) - Optional - Flags to be used when starting the activity. - **optionalIntentArguments** (string) - Optional - Additional arguments for the intent. - **dontStopAppOnReset** (boolean) - Optional - Should the app stop on reset. ### Request Example ```javascript app.appium.startActivity({ appPackage: 'com.example', appActivity: 'Activity' }); ``` ``` -------------------------------- ### Run with Extra Setup File Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/third-party-runners/cucumberjs-nightwatch-integration.md Execute Nightwatch tests with an extra setup file for Cucumber.js, specifying the path to the setup file. ```bash nightwatch examples/cucumber-js/features/step_definitions --require {/full/path/to/_extra_setup.js} ``` -------------------------------- ### Run Cucumber.js Example Tests Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/third-party-runners/cucumberjs-nightwatch-integration.md This command executes the example Cucumber.js tests located in the specified directory. Ensure Nightwatch is installed in your project to run this command. ```bash npx nightwatch examples/cucumber-js/features/step_definition ``` -------------------------------- ### Create New Project and Install Nightwatch Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/reporters/use-html-reporter.md Initializes a new project directory and installs Nightwatch and chromedriver using npm. ```bash mkdir ./test-project && cd ./test-project npm i nightwatch chromedriver ``` -------------------------------- ### Start Vite Dev Server Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/component-testing/vite-plugin.md Run this command in your project to start the Vite development server. ```bash npm run dev ``` -------------------------------- ### Install Firefox Extension via Options Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/api/firefox/index.md Configure the WebDriver session to install a Firefox extension by adding its path to the Options object. This example shows how to set preferences for the extension as well. ```javascript const firefox = require('selenium-webdriver/firefox'); const options = new firefox.Options() .addExtensions('/path/to/firebug.xpi') .setPreference('extensions.firebug.showChromeErrors', true); module.exports = { src_folders: ['tests'], test_settings: { default: { browserName: 'firefox', desiredCapabilities: options } } }; ``` ```javascript module.exports = { src_folders: ['tests'], test_settings: { default: { browserName: 'firefox', desiredCapabilities() { const firefox = require('selenium-webdriver/firefox'); const options = new firefox.Options() .addExtensions('/path/to/firebug.xpi') .setPreference('extensions.firebug.showChromeErrors', true); return options; } } } }; ``` -------------------------------- ### Initialize Nightwatch in an Existing Project Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/quickstarts/create-and-run-a-nightwatch-test.md Navigate to your existing project directory and run this command to install and set up Nightwatch. It will prompt for confirmation to install necessary packages. ```bash cd npm init nightwatch ``` -------------------------------- ### Install @nightwatch/react Plugin Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/component-testing/testing-react-components.md Install the React component testing plugin using npm. ```bash npm install @nightwatch/react ``` -------------------------------- ### Install Slack Reporter Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/reporters/use-slack-reporter.md Install the nightwatch-slack-reporter package as a development dependency using npm. ```bash npm i nightwatch-slack-reporter --save-dev ``` -------------------------------- ### Installing and Using an NPM Custom Reporter Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/reporters/create-custom-reporter.md Instructions for installing a custom reporter from NPM and then using it with the Nightwatch CLI. ```bash npm i ``` ```bash nightwatch --reporter= ``` -------------------------------- ### Install Vite Plugin Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/component-testing/vite-plugin.md Install the vite-plugin-nightwatch using npm. ```bash npm install vite-plugin-nightwatch ``` -------------------------------- ### Install Mochawesome Reporter Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/reporters/use-mochawesome-reporter.md Install the mochawesome reporter as a development dependency using npm. ```bash npm i mochawesome --save-dev ``` -------------------------------- ### Example Storybook Story with Nightwatch Extensions Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/component-testing/storybook-component-testing.md This example demonstrates a Storybook story written in CSF, extended with Nightwatch's test hooks and a custom test function. It shows how to define setup, pre-render, post-render, teardown hooks, and a play function for interactions, along with a Nightwatch-specific test. ```javascript import { userEvent, within } from '@storybook/testing-library'; import Form from './Form.jsx'; export default { title: 'Form', component: Form, async setup(browser) { console.log('setup hook', browser.capabilities) }, async preRender(browser) { console.log('preRender hook') }, async postRender(browser) { console.log('postRender hook') }, async teardown(browser) { console.log('teardown hook') }, } const Template = (args) =>
; // Component story for an empty form export const EmptyForm = Template.bind({}); // Component story simulating filling in the form export const FilledForm = Template.bind({}); FilledForm.play = async ({ canvasElement }) => { // Starts querying the component from its root element const canvas = within(canvasElement); // ๐Ÿ‘‡ Simulate interactions with the component await userEvent.type(canvas.getByTestId('new-todo-input'), 'outdoors hike'); await userEvent.click(canvas.getByRole('button')); }; FilledForm.test = async (browser, { component }) => { // ๐Ÿ‘‡ Run commands and assertions in the Nightwatch context await expect(component).to.be.visible; } ``` -------------------------------- ### Install Ava Test Runner Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/third-party-test-runners/ava.md Install Ava as a development dependency using npm. ```bash npm i ava --save-dev ``` -------------------------------- ### Working Example with User Actions API Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/api/useractions/index.md This example demonstrates a sequence of user actions including drag and drop, context click, and double click, with pauses in between. It retrieves a WebElement using the global `element()` utility before performing the actions. ```javascript describe('example with user actions api', function () { before(browser => browser.navigateTo('https://nightwatchjs.org')); it('demo test', async function (browser) { // retrieve the element; the actions api requires Selenium WebElement objects, // which can be retrieved using the global element() utility const btnElement = await element('a.btn-github').findElement(); await browser.perform(function() { // initiate the actions chain const actions = this.actions({async: true}); return actions .dragAndDrop(btnElement, {x: 100, y: 100}) .pause(500) .contextClick(btnElement) .pause(500) .doubleClick(btnElement) .pause(500) }); }); }); ``` -------------------------------- ### Install mocha-junit-reporter Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/third-party-runners/using-mocha.md Install the mocha-junit-reporter as a development dependency using npm. ```bash npm i mocha-junit-reporter --save-dev ``` -------------------------------- ### Run Development Server Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/README.md Start the development server for the Nightwatch.js documentation website. ```bash npm start ``` -------------------------------- ### Install Dependencies and Run Tests Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/ci-integrations/run-nightwatch-on-jenkins.md Use these commands in an 'Execute shell' build step to install project dependencies and run Nightwatch tests on a Jenkins instance. ```bash npm install npm test ``` -------------------------------- ### Install @nightwatch/storybook Plugin Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/component-testing/storybook-component-testing.md Install the Storybook plugin for Nightwatch as a development dependency using npm. ```bash npm i @nightwatch/storybook --save-dev ``` -------------------------------- ### Working Example with element() Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/api/element.md Demonstrates navigating to a page, adding a to-do item using `element()` to define selectors, and verifying the addition and completion of the task. This example requires Nightwatch.js v2 or later. ```javascript describe('angularjs homepage todo list', function() { // using the new element() global utility in Nightwatch 2 to init elements // before tests and use them later const todoElement = element('[ng-model="todoList.todoText"]'); const addButtonEl = element('[value="add"]'); it('should add a todo using global element()', function() { // adding a new task to the list browser .navigateTo('https://angularjs.org') .sendKeys(todoElement, 'what is nightwatch?') .click(addButtonEl); // verifying if there are 3 tasks in the list expect.elements('[ng-repeat="todo in todoList.todos"]').count.to.equal(3); // verifying if the third task if the one we have just added const lastElementTask = element({ selector: '[ng-repeat="todo in todoList.todos"]', index: 2 }); expect(lastElementTask).text.to.equal('what is nightwatch?'); // find our task in the list and mark it as done lastElementTask.findElement('input', function(inputResult) { if (inputResult.error) { throw inputResult.error; } const inputElement = element(inputResult.value); browser.click(inputElement); }); // verify if there are 2 tasks which are marked as done in the list expect.elements('*[module=todoApp] li .done-true').count.to.equal(2); }); }); ``` -------------------------------- ### Install Dependencies with npm Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/ci-integrations/run-nightwatch-on-bamboo.md Use this npm task to install project dependencies. Ensure Node.js is configured correctly in Bamboo. ```bash npm install ``` -------------------------------- ### Install @nightwatch/angular Plugin Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/component-testing/testing-angular-components.md Install the Angular plugin using npm. This is the first step to enable Angular component testing. ```bash npm install @nightwatch/angular ``` -------------------------------- ### Install Test Doubles Plugin Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/writing-tests/test-doubles.md Install the official test doubles plugin from NPM. This command should be run in your project's root directory. ```bash npm i @nightwatch/testdoubles --save-dev ``` -------------------------------- ### Setup Android Emulator Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/mobile-web-testing/upgrade-chrome-on-emulator.md Run this command to set up the Android emulator if your system does not meet the prerequisites. ```bash npx @nightwatch/mobile-helper android ``` -------------------------------- ### Install Chrome APKs on Emulator Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/mobile-web-testing/upgrade-chrome-on-emulator.md Install multiple APK files from a directory onto an Android emulator using the mobile helper's adb install-multiple command. Ensure the emulator is running and the ANDROID_HOME environment variable is set. ```bash npx @nightwatch/mobile-helper android.adb install-multiple chrome_bundle/*.apk ``` -------------------------------- ### Install and Run @nightwatch/chrome-recorder CLI Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/writing-tests/chrome-devtools-recorder.md Install the @nightwatch/chrome-recorder package and run the CLI tool to convert DevTools recordings to Nightwatch tests. The tool prompts for the recording location and specifies the output directory. ```bash npm install @nightwatch/chrome-recorder npx @nightwatch/chrome-recorder ``` -------------------------------- ### Validate iOS Simulator Setup Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/mobile-app-testing/installation.md Execute this command to validate your Nightwatch.js installation by running sample tests on an iOS simulator. This confirms your setup for iOS testing. ```bash npx nightwatch nightwatch/examples/mobile-app-tests/wikipedia-ios.js --env app.ios.simulator ``` -------------------------------- ### Install System Image with Play Store Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/mobile-web-testing/upgrade-chrome-on-emulator.md Install a system image that includes the Google Play Store, necessary for upgrading Chrome via the Play Store method. Follow the prompts to select API level, system image type (google_apis_playstore), and architecture. ```bash npx @nightwatch/mobile-helper android install --system-image ``` -------------------------------- ### Initialize Nightwatch Project Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/browser-extension-testing/chrome-extension.md Sets up a new Nightwatch project. Ensure to select the 'Chrome' browser during the interactive setup. ```bash cd /path/to/project/directory npm init nightwatch ``` -------------------------------- ### Install Firefox Extension via Configuration Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/api/commands/index.md Configure Nightwatch to install a Firefox extension during WebDriver session setup using a static options object. Ensure the extension path is correct. ```javascript const firefox = require('selenium-webdriver/firefox'); const options = new firefox.Options() .addExtensions('/path/to/firebug.xpi') .setPreference('extensions.firebug.showChromeErrors', true); module.exports = { src_folders: ['tests'], test_settings: { default: { browserName: 'firefox', desiredCapabilities: options } } }; ``` -------------------------------- ### Initialize Storybook Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/component-testing/storybook-component-testing.md Run this command to set up Storybook in an existing React project. ```bash npx storybook init ``` -------------------------------- ### Setup Mobile Web Testing Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/quickstarts/create-and-run-a-nightwatch-test.md Choose whether to set up Nightwatch for running tests on real or virtual mobile devices. This includes the setup of necessary SDKs, libraries, and virtual devices. ```bash Setup testing on Mobile devices as well? (Use arrow keys) Yes โฏ No, skip for now ``` -------------------------------- ### Test Script with client.init() (Older Syntax) Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/api/index.md An example using the older `client` syntax for initializing the session. While functional, `browser` is the preferred modern approach. ```javascript module.exports = { demoTest: function (client) { client.init(); } }; ``` -------------------------------- ### Perform a GET API Request Test Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/writing-tests/api-testing.md Example of making a GET request to an API endpoint using supertest within a Nightwatch test. It asserts the status code, content type, and checks the response body length. ```javascript describe('api testing', function () { it('get api test', async function({supertest}) { await supertest .request("https://petstore.swagger.io/v2") .get("/pet/findByStatus?status=available") .expect(200) .expect('Content-Type', /json/) .then(function(response){ expect(response._body.length).to.be.greaterThan(0); }); }); }); ``` -------------------------------- ### Run an Ava test with Nightwatch.js Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/third-party-test-runners/ava.md This snippet shows an example Ava test that uses Nightwatch.js for browser automation. Ensure Ava is installed and configured. ```javascript const test = require('ava'); const await_nightwatch_browser = require('../../../_setup-nightwatch-env.js'); test('duckduckgo example', await_nightwatch_browser, async function(t) { browser .navigateTo('https://www.ecosia.org/') .waitForElementVisible('body') const titleContains = await browser.assert.titleContains('Ecosia'); t.is(titleContains.passed, true); const visible = await browser.assert.visible('input[type=search]') t.is(visible.passed, true); t.pass(); }); ``` -------------------------------- ### Validate Android Emulator Setup Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/mobile-app-testing/installation.md Run this command to validate your Nightwatch.js installation by executing sample tests on an Android emulator. Ensure you have the necessary configurations set up. ```bash npx nightwatch nightwatch/examples/mobile-app-tests/wikipedia-android.js --env app.android.emulator ``` -------------------------------- ### Serve Built Website Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/README.md Quickly serve the generated static files from the 'out' folder using PostDoc. ```bash npx postdoc preview ``` -------------------------------- ### Nightwatch Test with Mocha Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/third-party-runners/using-mocha.md Example of a Nightwatch test suite structured using Mocha. Requires manual setup for Selenium server and involves more boilerplate code. ```javascript var nightwatch = require('nightwatch'); describe('Github', function() { var client = nightwatch.initClient({ silent : true }); var browser = client.api(); this.timeout(99999999); before(function() { browser.perform(function() { console.log('beforeAll') }); }); beforeEach(function(done) { browser.perform(function() { console.log('beforeEach') }); client.start(done); }); it('Demo test GitHub', function (done) { browser .url('https://github.com/nightwatchjs/nightwatch') .waitForElementVisible('body', 5000) .assert.title('nightwatchjs/nightwatch ยท GitHub') .waitForElementVisible('body', 1000) .assert.visible('.container .breadcrumb a span') .assert.containsText('.container .breadcrumb a span', 'nightwatch', 'Checking project title is set to nightwatch'); client.start(done); }); afterEach(function() { browser.perform(function() { console.log('afterEach') }); }); after(function(done) { browser.end(function() { console.log('afterAll') }); client.start(done); }); }); ``` -------------------------------- ### Create Tests Directory and Sample Test File Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/configuration/define-test-environments.md Creates the 'tests' directory and a sample Nightwatch test file within it. ```bash mkdir tests && nano ./tests/sample-nightwatch-test.js ``` -------------------------------- ### Nightwatch Globals Setup for Vite Server Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/writing-tests/write-component-tests-for-react.md Set up the Nightwatch globals file to manage the Vite dev server lifecycle. This includes starting the server before tests and closing it afterwards, and setting the launch URL. ```javascript const {setup} = require('@nightwatch/react'); let viteServer; module.exports = { async before() { viteServer = await setup({ // you can optionally pass an existing vite.config.js file // viteConfigFile: '../vite.config.js' }); // This will make sure the launch Url is set correctly when mounting the React component this.launchUrl = `http://localhost:${viteServer.config.server.port}`; }, async after() { await viteServer.close(); } } ``` -------------------------------- ### Complete BDD Syntax and Configuration Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/writing-tests/using-bdd-describe.md A comprehensive example showcasing various configurations available within a describe block, including settings, capabilities, unit test flags, failure handling, skipping tests, timeouts, and hooks like before() and after(). ```javascript describe('homepage test with describe', function() { // All current settings are available via this.settings // console.log('Settings', this.settings); // testsuite specific capabilities // this.desiredCapabilities = {}; // Enable this if the current test is a unit/integration test (i.e. no Webdriver session will be created) // this.unitTest = false // Set this to false if you'd like the browser window to be kept open in case of a failure or error (useful for debugging) // this.endSessionOnFail = true // Set this to false if you'd like the rest of the test cases/test steps to be executed in the event of an assertion failure/error // this.skipTestcasesOnFail = true // Set this to true if you'd like this test suite to be skipped by the test runner // this.disabled = false // this.retries(3); // this.suiteRetries(2); // Control the assertion and element commands timeout until when an element should be located or assertion passed // this.timeout(1000) // Controll the polling interval between re-tries for assertions or element commands // this.retryInterval(100); before(function(browser) { this.homepage = browser.page.home(); }); it('startHomepage', () => { this.homepage.navigate(); this.homepage.expect.section('@indexContainer').to.be.not.visible; }); // Run only this testcase /* it.only('startHomepage', () => { this.homepage.navigate(); }); */ // skipped testcase: equivalent to: test.skip(), it.skip(), and xit() xtest('async testcase', async browser => { const result = await browser.getText('#navigation'); console.log('result', result.value) }); test('version dropdown is enabled', browser => { const navigation = this.homepage.section.navigation; const navbarHeader = navigation.section.navbarHeader; navbarHeader.expect.element('@versionDropdown').to.be.enabled; }); after(browser => browser.end()); }); ``` -------------------------------- ### React Component Test with Interaction and Lifecycle Hooks Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/component-testing/write-jsx-react-tests.md An advanced example showcasing interaction tests using `play()` with Testing Library utilities and defining global and component-level lifecycle hooks (`setup`, `teardown`, `preRender`, `postRender`). ```javascript import { fireEvent, within } from '@testing-library/dom'; import Form from '../components/Form.jsx'; export default { title: 'Form Component', component: Form, // executed before all the individual component stories; runs in Node context async setup(browser) { console.log('global setup hook', browser.capabilities) }, // executed after all the individual component stories; runs in Node context async teardown(browser) { console.log('global teardown hook') }, // executed before each individual component story; runs in Node context async preRender(browser, context) { // context is made of {id, name, title} console.log('preRender', context.id); }, // executed after each individual component story; runs in Node context async postRender(browser, context) { // context is made of {id, name, title} console.log('postRender', context.id); } } export const AnotherForm = Object.assign(() => , { async preRender() {}, async postRender() { console.log('after mount', window); }, async play({canvasElement, args}) { console.log('play function', args); const root = within(canvasElement); const input = root.getByTestId('new-todo-input'); fireEvent.change(input, { target: { value: 'another one bites the dust' } }); return { fromPlay: input } }, test: async (browser, {component, result}) => { console.log('Result from play', result) await expect(component).to.be.visible; await expect(component.find('input')).to.have.property('value').equal('another one bites the dust'); } }); ``` -------------------------------- ### Set up a POST route for the mock server Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/writing-tests/api-testing.md Configure a POST route on the mock server to handle incoming requests and send a JSON response. This is the first step in setting up API endpoints for testing. ```javascript await mockServer.setup((app) => { app.post('/api/v1/datasets/', function (req, res) { res.status(200).json({ id: 'test-dataset-id' }); }); }); ``` -------------------------------- ### Create a new Nightwatch project directly Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/quickstarts/create-and-run-a-test-with-selenium-server.md This command initializes a new Nightwatch project in a specified directory with a single command. Press 'y' to confirm package installation when prompted. ```bash npm init nightwatch <directory-name> ``` -------------------------------- ### Install Cucumber.js Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/third-party-runners/cucumberjs-nightwatch-integration.md Install the Cucumber.js library as a development dependency in your project. ```bash npm i @cucumber/cucumber --save-dev ``` -------------------------------- ### View PostDoc CLI Help Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/README.md Display the available options for the PostDoc command-line interface. ```bash npx postdoc --help ``` -------------------------------- ### Install Jest Test Runner Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/third-party-test-runners/jest.md Install Jest as a development dependency for your project. ```bash npm i jest --save-dev ``` -------------------------------- ### Install Storybook Accessibility Addon Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/component-testing/storybook-component-testing.md Install the @storybook/addon-a11y package as a development dependency. ```bash npm i @storybook/addon-a11y --save-dev ``` -------------------------------- ### Connect to Emulator Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/mobile-web-testing/upgrade-chrome-on-emulator.md Connect to your Android emulator using the mobile helper. Select the AVD you created, which includes the Play Store, to proceed with updating Chrome. ```bash npx @nightwatch/mobile-helper android connect --emulator ``` -------------------------------- ### Info Admonition Example Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/contributing/index.md An informational note explaining the purpose of an example test. ```html
The below commands runs an example test which opens the search engine [Ecosia.org](https://www.ecosia.org/), types the term "nightwatch" into the search input field, then verifies if the results page contains the text "Nightwatch.js".
``` -------------------------------- ### Create Project Directory Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/configuration/define-test-environments.md Creates a new directory for the Nightwatch test project and navigates into it. ```bash mkdir ./test-project && cd ./test-project ``` -------------------------------- ### Example Output with Environment Globals Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/concepts/test-globals.md This shows the expected console output when running tests with the 'integration' environment, demonstrating that the environment-specific global `myGlobalVar` has been applied. ```bash myGlobalVar is: "integrated global" ``` -------------------------------- ### Install chromedriver for Android Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/mobile-app-testing/running-tests.md Install the latest chromedriver development dependency for Android testing. ```bash npm i chromedriver@latest --save-dev ``` -------------------------------- ### Install Nightwatch and Chromedriver Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/configuration/define-test-environments.md Install the necessary packages for Nightwatch and ChromeDriver using npm. ```bash npm i nightwatch chromedriver ``` -------------------------------- ### Enable Automatic WebDriver Process Management Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/configuration/web-driver-settings.md Set `start_process` to true to enable automatic management of the WebDriver server. Specify the `server_path` to the binary file. ```javascript module.exports = { // ... other configurations webdriver: { start_process: true, server_path: 'path/to/your/chromedriver' } }; ``` -------------------------------- ### Create a new Nightwatch project directory Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/quickstarts/create-and-run-a-test-with-selenium-server.md Use these bash commands to create a new directory, navigate into it, and initialize a new Nightwatch project using the latest version. ```bash mkdir <directory-name> cd <directory-name> npm init nightwatch@latest ``` -------------------------------- ### Install Nightwatch VRT Plugin Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/writing-tests/visual-regression-testing.md Install the @nightwatch/vrt plugin as a development dependency using npm. ```bash npm i @nightwatch/vrt --save-dev ``` -------------------------------- ### Create Nightwatch Configuration File Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/configuration/define-test-environments.md Creates an empty nightwatch.conf.js file using the nano editor. ```bash nano nightwatch.conf.js ``` -------------------------------- ### Install GeckoDriver NPM Package Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/browser-drivers/geckodriver.md Install the geckodriver NPM package as a development dependency in your project. ```javascript npm install geckodriver --save-dev ``` -------------------------------- ### Example Browser Capabilities Response Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/concepts/session-capabilities.md This snippet illustrates the supported capabilities returned by the WebDriver service after a browser session is successfully created. It includes browser version, specific browser options, and session ID. ```bash Response 200 POST /session (724ms) { value: { capabilities: { acceptInsecureCerts: false, browserName: 'chrome', browserVersion: '102.0.5005.61', chrome: { chromedriverVersion: '101.0.4951.41 (93c720...)' }, 'goog:chromeOptions': { debuggerAddress: 'localhost:52470' }, networkConnectionEnabled: false, pageLoadStrategy: 'normal', platformName: 'mac os x', proxy: {}, setWindowRect: true, strictFileInteractability: false, timeouts: { implicit: 0, pageLoad: 300000, script: 30000 }, unhandledPromptBehavior: 'dismiss and notify', 'webauthn:extension:credBlob': true, 'webauthn:extension:largeBlob': true, 'webauthn:virtualAuthenticators': true }, sessionId: '15d21f2132ff0675a97ca419bf6fbd4' } } ``` -------------------------------- ### Install Jest Nightwatch Environment Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/third-party-test-runners/jest.md Install the `jest-environment-nightwatch` package to enable Nightwatch functionality within Jest. ```bash npm i jest-environment-nightwatch --save-dev ``` -------------------------------- ### Set and Reset Device Dimensions Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/mobile-web-testing/override-device-dimensions.md This example demonstrates how to set specific device dimensions and then reset them back to their original values using `browser.setDeviceDimensions()` without arguments. This is useful for testing different states of responsiveness. ```javascript describe('modify device dimensions', function() { it('modifies the device dimensions and then resets it', function() { browser .setDeviceDimensions({ width: 400, height: 600, deviceScaleFactor: 50, mobile: true }) .navigateTo('https://www.google.com') .pause(1000) .setDeviceDimensions() // resets the device dimensions .navigateTo('https://www.google.com') .pause(1000); }); }); ``` -------------------------------- ### Run Nightwatch with a Test File and a Folder Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/running-tests/nightwatch-runner.md Example of running a single test file and an entire folder of tests using the Nightwatch CLI. ```bash nightwatch tests/one/test.js tests/utils ``` -------------------------------- ### Install Appium XCUITest Driver for iOS Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/mobile-app-testing/installation.md Installs the necessary driver for Appium to interact with iOS applications. ```bash npx appium driver install xcuitest ``` -------------------------------- ### Install Appium as a Development Dependency Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/mobile-app-testing/installation.md Install Appium 2 as a development dependency in your project using npm. ```bash npm i appium --save-dev ``` -------------------------------- ### Install Nightwatch Teamcity Reporter Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/reporters/use-teamcity-reporter.md Install the nightwatch-teamcity package as a development dependency in your project using npm. ```bash npm i nightwatch-teamcity --save-dev ``` -------------------------------- ### Basic Test Script with browser.init() Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/api/index.md A standard test script using the `browser` object to initialize the session. This is the most common way to start a test. ```javascript module.exports = { demoTest: function (browser) { browser.init(); } }; ``` -------------------------------- ### Install Nightwatch Allure Reporter Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/reporters/use-nightwatch-allure-reporter.md Install the nightwatch-allure package as a development dependency in your project using npm. ```bash npm i nightwatch-allure --save-dev ``` -------------------------------- ### Initialize Nightwatch Project in App Mode Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/mobile-app-testing/installation.md Use this command to directly initiate Nightwatch installation for mobile app testing, bypassing other testing types. ```bash npm init nightwatch@latest -- --app ``` -------------------------------- ### Selecting an Option from a Dropdown List Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/api/method/click.md This example shows how to use the `click` command twice to select a specific option from a dropdown list. ```APIDOC ## click (Dropdown Selection) ### Description Used to select an option from a dropdown list by first clicking the select element and then clicking the desired option. ### Method `browser.click(selector1).click(selector2, [callback])` ### Parameters #### Selector 1 (Dropdown Trigger) - **selector1** (string) - Required - The CSS selector for the dropdown select element. #### Selector 2 (Option) - **selector2** (string) - Required - The CSS selector for the specific option within the dropdown to select. #### Callback - **callback** (function) - Optional - A function to execute after the second click action. - **result** (object) - Contains the status of the click operation. - **status** (number) - 0 indicates success. ### Request Example ```javascript browser .url('https://www.w3.org/') .waitForElementVisible('#region_form') .click('#region_form select') // Click the select element .click('#region_form select option[value="all"]', function(result) { this.assert.strictEqual(result.status, 0); }) ``` ### Response #### Success Response The callback function receives a result object indicating the success of the second click operation. #### Response Example ```json { "status": 0 } ``` ### Possible Errors - `element not visible`: The target element is not visible on the page. ``` -------------------------------- ### Install Appium UiAutomator2 Driver for Android Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/mobile-app-testing/installation.md Install the necessary UiAutomator2 driver for Appium to interact with Android devices. ```bash npx appium driver install uiautomator2 ``` -------------------------------- ### Ava Configuration Options Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/third-party-test-runners/ava.md Example Ava configuration object, showing options for file matching, concurrency, and environment variables. This can be placed in package.json or an ava.config.js file. ```json { "ava": { "files": [ "test/**/*", "!test/exclude-files-in-this-directory", "!**/exclude-files-with-this-name.* " ], "match": [ // "*oo", // "!foo" ], "concurrency": 5, "failFast": true, "failWithoutAssertions": false, "environmentVariables": { "MY_ENVIRONMENT_VARIABLE": "some value" }, "verbose": true, "nodeArguments": [ "--trace-deprecation", "--napi-modules" ] } } ``` -------------------------------- ### Start Session Configuration Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/reference/defaults.md Determines whether to automatically start the Selenium/WebDriver session. Set to false for unit tests. ```javascript start_session: true, ``` -------------------------------- ### Configure AWS CLI Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/configuration/aws-devicefarm-settings.md Install and configure the AWS CLI to set up credentials for Node.js. This is a prerequisite for using the AWS SDK. ```bash aws configure ``` -------------------------------- ### Confirm Nightwatch package installation Source: https://github.com/nightwatchjs/nightwatch-docs/blob/versions/3.0/docs/guide/quickstarts/create-and-run-a-test-with-selenium-server.md When prompted during the 'npm init nightwatch' command, press 'y' to proceed with the installation of the 'create-nightwatch' package. ```bash โฏ npm init nightwatch Need to install the following packages: create-nightwatch Ok to proceed? (y) ```