0% found this document useful (0 votes)
264 views29 pages

Night Watch Notes

Wings 1 notes and mcqs

Uploaded by

LATHIKA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
264 views29 pages

Night Watch Notes

Wings 1 notes and mcqs

Uploaded by

LATHIKA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

When it comes to automation testing along with Selenium and Javascript, there is one

framework that never fails to take the spotlight and that is NightwatchJS.
Nightwatch.js is an open-source automated testing framework that is powered by
Node.js and provides complete E2E (end to end) solutions to automation testing with
Selenium Javascript be it for web apps, browser apps, and websites.
This NightwatchJS tutorial will help you explore its advantages and how it can be
installed for flawless automation testing.
Table of Contents

• What is Nighwatch.js Framework?


• Features of Nightwatch.js Framework
• Advantages of Nightwatch.js
• How does Nightwatch.js work?
• Prerequisites of Nightwatch.js
• Writing and Running Nightwatch Tests
• How to use Nightwatch with CucumberJS
• Executing Individual Feature Files or Scenarios

What is Nighwatch.js Framework?


Nightwatch.js framework is a Selenium-based test automation framework, written
in Node.js and uses the W3C WebDriver API (formerly Selenium WebDriver). It works
by communicating over a restful HTTP API with a WebDriver server (such as
ChromeDriver or Selenium Server). The protocol is defined by the W3C WebDriver
spec, which is derived from the JSON Wire protocol.
It is a complete end-to-end testing solution that aims to simplify writing automated tests.
And effortlessly sets up the way for Continuous Integration.
Learn More: End-to-End Microservices Testing

Features of Nightwatch.js Framework


• In-Built Test Runner: It comes with an inbuilt command-line test runner suite
that helps in executing the automated tests.
• Browser Automation: Nightwatch.js is an easy-to-use End-to-End testing
solution for web-browser applications and websites. It is useful for beginners as it
is written in Node.js.
• Test Strategy: It has the feature to execute the tests efficiently and can be
performed in multiple ways such as sequentially, parallelly, or in groups, and
tags.
• Cloud Testing Support: Nightwatch.js is compatible with different cloud testing
providers such as BrowserStack.
• Distinct Syntax: The syntax of Nightwatch.js is simple and yet it is powerful
which helps developers to write tests and deliver them in a very short span of
time.
• Page Object Support: The framework is easy and simple for beginners to
understand as it provides Page Object Model support. It is also compatible with
both CSS and Xpath selectors.
• Selenium Server: It has the ability to automatically control the standalone
Selenium server with a built-in JUnit XML reporting structure.
• Continuous Integration: It offers good support for Continuous Integration and
hence can be easily used to integrate tests with the continuous build processing
systems such as TeamCity, Jenkins, Hudson, etc.
Must Read: Choosing Between Nightwatch, Protractor & Mocha

Advantages of Nightwatch.js
• Has a robust configuration and a lightweight framework
• Can be easily integrated with cloud service providers like Browserstack for web
and mobile application testing
• Low code maintenance
• Improves the test structure
• Better performance
• Allows configuration with Cucumber to build a BDD (Behaviour Driven
Development) setup.
How does Nightwatch.js work?
In order to establish the communication and relay requests, Nightwatch.js employs a
restful HTTP API with the help of an HTTP protocol laid down by the W3C WebDriver
API and extracted from the JSONWire protocol. It communicates over a restful HTTP
API by utilizing the HTTP protocol that is defined by W3C WebDriver API and derived
from the JSONWire protocol.
Nightwatch.js issues dual requests to the WebDriver server in order to carry out any
kind of browser interaction. This request can be issued with the help of a command, an
assertion, or an action that is available on page objects of the web application.

• The first request is sent to the Selenium server, for creating a session with the
browser. It locates the target element on which the action has to be performed,
with the help of CSS or XPath selector of that object.

• The second request performs the actual operation of command or assertion on


the web element.
Prerequisites of Nightwatch.js
Below are some basic prerequisites that are required to get started with NightwatchJS:

• Node.js: Nightwatch module is built on top of Node.js, so it clearly indicates that


Node.js is required to be installed on the system.
• Node Package Manager (npm): Once Node.js is successfully installed, the
node’s package manager i.e. npm should also be installed. Now, to install the
latest version using the npm command-line tool, the below command is executed
(here ‘g’ is for installing globally):
$ npm install -g nightwatch

Once, npm is installed, run the below command to install Nightwatch and save it as a
dev dependency.
$ npm install nightwatch --save-dev

The next step is to install chromedriver/geckodriver and to save it as a dev dependency


for running the execution on the required browser.
$ npm install chromedriver --save-dev
Once all the above steps are done:
Create a Package.json file for the test settings and dependencies
Package.json
{

"name": "demotest",

"version": "1.0.0",

"description": "NightwatchJS Practise test",

"main": "index.js",

"scripts": {

"test": "nightwatch"

},

"author": "",

"license": "ISC",

"devDependencies": {

"chromedriver": "^101.0.0",

"nightwatch": "^2.1.4"

Create a nightwatch.conf.js for webdriver and test settings with Nightwatch:


nightwatch.conf.js
const chromedriver = require('chromedriver');

module.exports = {

src_folders : ["tests"], //tests is a folder in workspace that has the step


definitions

test_settings: {
default: {

webdriver: {

start_process: true,

server_path: chromedriver.path,

port: 4444,

cli_args: ['--port=4444']

},

desiredCapabilities: {

browserName: 'chrome'

};

Writing and Running Nightwatch Tests


We create a JavaScript file named demo.js for running a test through Nightwatch with
the command. This file needs to be created inside a folder named “tests” as we have
specified for src_folders in nightwatch.conf.js, shown in the above step.
demo.js
//demo.js is a JS file under tests folder

module.exports = {

'step one: navigate to google' : function (browser) { //step one

browser

.url('https://www.google.com')
.waitForElementVisible('body', 1000)

.setValue('input[type=text]', 'nightwatch')

.waitForElementVisible('input[name=btnK]', 1000)

},

'step two: click input' : function (browser) { //step two

browser

.click('input[name=btnK]')

.pause(1000)

.assert.containsText('#main', 'Night Watch')

.end(); //to close the browser session after all the steps

Next, we run the below command.


npm_test.sh
$ npm test

On running this command, it picks the value “nightwatch” from “test” key in
package.json file that further hits the nightwatch api to trigger the URL in chromedriver.
Also, there can be one or more than one step in demo.js(step definition js) file as per
the requirement of the test cases.
It is also a good practice to maintain a separate .js file for page objects which consists
of the locator strategy and selectors of the UI elements.
pageObjects.js
module.exports = {

elements: {

googleInputBox: '//input[@type="text"]',
searchButton: '(//input[@value="Google Search"])[2]',

headingText: `//h3[contains(text(),'Nightwatch.js')]`

The locator strategy is set to CSS and Xpath to inspect the UI elements.
async_function.sh
locateStrategy: async function (selector) { return await selector.startsWith('/') ?
'xpath' : 'css selector'; }

Nightwatch.conf.js file is also updated with the page_objects location.


const chromedriver = require('chromedriver');

module.exports = {

src_folders : ["tests"], //tests is a folder in workspace that has the step


definitions

page_objects_path: 'page_objects/', //page_objects folder where selectors are saved

test_settings: {

default: {

webdriver: {

start_process: true,

server_path: chromedriver.path,

port: 4444,

cli_args: ['--port=4444']

},

desiredCapabilities: {

browserName: 'chrome'
}

};

How to use Nightwatch with CucumberJS


Cucumber is a tool that supports Behavior Driven Development (BDD) and allows us to
write tests in simple English language in Given, When, and Then format.
In order to use NightwatchJS with cucumber, we need to first add cucumber as a dev
dependency in the code.
$ npm install --save-dev nightwatch-api nightwatch @cucumber/cucumber chromedriver
cucumber-pretty

The below package.json can be used next for the test settings and dependencies.
package.json
{

"name": "nightwatchdemo",

"version": "1.0.0",

"description": "To learn automation by nightwatch",

"main": "google.js",

"scripts": {

"test": "nightwatch",

"test:cucumber": "cucumber-js --require cucumber.conf.js --require tests --format


node_modules/cucumber-pretty",

"e2e-test": "cucumber-js --require cucumber.conf.js --require step-definition"

},

"author": "",
"license": "ISC",

"dependencies": {

"cucumber": "^5.1.0",

"cucumber-pretty": "^1.5.0"

},

"devDependencies": {

"chromedriver": "^2.40.0",

"nightwatch": "^2.1.4",

"nightwatch-api": "^2.2.0"

After this, we need to create nightwatch.js.conf file.


nightwatch.conf.js
const chromedriver = require('chromedriver');

module.exports = {

test_settings: {

default: {

webdriver: {

start_process: true,

server_path: chromedriver.path,

port: 4444,

},

desiredCapabilities: {
browserName: 'chrome'

};

The next step is to create a file cucumber.conf.js in the root folder that has the setup of
starting and closing the webdriver sessions.
cucumber.conf.js
const { setDefaultTimeout, AfterAll, BeforeAll } = require('cucumber');

const { createSession, closeSession, startWebDriver, stopWebDriver } =


require('nightwatch-api');

setDefaultTimeout(60000);

BeforeAll(async () => {

await startWebDriver();

await createSession();

});

AfterAll(async () => {

await closeSession();

await stopWebDriver();

});

Then we create a feature file that has the test scenarios in Given, When, Then format.
google.feature
Feature: Google Search
Scenario: Searching Google

Given I open Google's search page

Then the title is "Google"

And the Google search form exists


It’s time to create matching step definitions used in the feature file for Cucumber to be
able to understand and execute the feature file. For adding the feature file, we will
create a folder named “features” in the project root folder. All the feature files are usually
maintained inside this folder.
The following step would be to create the .js files, this file needs to be under the “step-
definition” folder.
google.js
const { client } = require('nightwatch-api');

const { Given, Then, When } = require('cucumber');

Given(/^I open Google's search page$/, () => {

return client.url('http://google.com').waitForElementVisible('body', 1000);

});

Then(/^the title is "([^"]*)"$/, title => {

return client.assert.title(title);

});

Then(/^the Google search form exists$/, () => {

return client.assert.visible('input[name="q"]');

});

The next step is to create an npm script.


In package.json, we use the npm script to define the commands to execute the
Cucumber tests. Here we have given the name as “e2e-test”
"scripts": {

"e2e-test": "cucumber-js --require cucumber.conf.js --require step-definitions"

},

Now, trigger the following command from the terminal to run the tests
npm_run.js
$ npm run e2e-test

Executing Individual Feature Files or


Scenarios
Below are some commands for running feature files or scenarios.
For running a single feature file
npm run e2e-test -- features/file1.feature

For running multiple feature files


npm run e2e-test -- features/file1.feature features/file2.feature

For running a Scenario by its line number


npm run e2e-test -- features/my_feature.feature:3

NightwatchJS automates the entire test suite quickly with minimal configuration and is
readable as well as very easy to maintain and update. It also supports parallel testing of
cases which proves to be another time-efficient feature of it. On the other hand,
Nightwatch-Cucumber also is a great module for linking the accessibility of Cucumber.js
with the robust testing framework of Nightwatch.js.
However, to get the best results while automation testing, it is highly recommended to
test on a real device cloud.
Re-Notes:

The first step is to create an empty folder and navigate to it. To


install Nightwatch in this folder, need run command:
npm install Nightwatch

Configuration

For Windows, you need to create nightwatch.js in the root folder and write in this
file path to runner.js, file which required for start nightwatch process, by default
you need to add to this file
require('./node_modules/nightwatch/bin/runner');
For macOS and Linux this is not required.

Next, you need to create configuration file nightwatch.json. It should be placed in


the project’s root folder because it specifies various configuration settings like
test environments, test file paths, and selenium specific settings. This is what the
configuration file looks like:
{
"src_folders": ["tests"],
"output_folder": "reports",
"custom_commands_path": "",
"custom_assertions_path": "",
"page_objects_path": "",
"globals_path": "",

"selenium": {
"start_process": true,
"server_path": "./lib/selenium-server-standalone-3.9.1.jar",
"log_path": "./reports",
"host": "127.0.0.1",
"port": 4445,
"cli_args": {
"webdriver.chrome.driver": "./lib/drivers/chromedriver.exe",
"webdriver.gecko.driver": "./lib/drivers/geckodriver.exe",
"webdriver.edge.driver": "./lib/drivers/MicrosoftWebDriver.exe"
}
},

"test_settings": {
"default": {
"launch_url": "http://localhost",
"selenium_port": 4445,
"selenium_host": "localhost",
"silent": true,
"screenshots": {
"enabled": true,
"path": "./reports/screenshots"
},
"desiredCapabilities": {
"browserName": "chrome",
"marionette": true,
"javascriptEnabled": true,
"acceptSslCerts": true
}
},
"chrome": {
"desiredCapabilities": {
"browserName": "chrome"
}
},

"firefox": {
"desiredCapabilities": {
"browserName": "firefox"
}
},

"edge": {
"desiredCapabilities": {
"browserName": "MicrosoftEdge"
}
}
}
}
Here is a brief description of the parameters of the nightwatch.json file:

• src_folders: An array of folders (excluding subfolders) where the tests are


located.
• output_folder: The location where the JUnit XML report files (XML reports,
selenium log and screenshots) will be saved.
• page_objects_path: Location(s) where page object files will be loaded from
• globals_path: Location of an external globals module which will be loaded
and made available to the test as a property globals on the main client
instance. Globals can also be defined/overwritten inside a test_settings
environment.
• Selenium: An object containing Selenium Server related configuration
options. For us, it’s important to set the start_process parameter to true
because in this case, Selenium Server will start automatically. Also for the
server_path and webdriver paths required to set proper folder specified.
• test_settings: This object contains all the test related options. The important
part of the default settings is the desiredCapabilities object where we
specify chrome as the default browser so Nightwatch will run tests with this
browser by default.

Sample Test:

module.exports = {
'Bing search test' : function (client) {
client
.url('http://www.bing.com')
.waitForElementVisible('body', 1000)
.assert.title('Bing')
.waitForElementVisible('#sb_form_q', 1000)
.setValue('#sb_form_q', 'nightwatch.js')
.submitForm('#sb_form_q')
.pause(1000)
.assert.containsText('#b_results > li:nth-child(1) > h2',
'Nightwatch.js | Node.js powered End-to-End testing …')
.click('#b_results > li:nth-child(1) > h2')
.assert.title('Nightwatch.js | Node.js powered End-to-End testing
framework')
.end();
}
};
This test:

• Navigate to Bing page


• Assert that you in the properly page
• Enter “nightwatch.js” to the search field and click the search button
• Assert that first search result is Nightwatch page and navigate to this page
• Assert that page load properly

You may save this test to the tests folder


To run this test, you need to enter a command from root folder:
node nightwatch tests/bing_test.js
If you made all steps properly, you would see that Google Chrome browser start
and test run. In the console you will see such result:

Nightwatch example:
NIGHTWATCH COMMANDS:

Actions

• browser.click: Click on an element.

javascript
Copy code
browser.click('#selector');

• browser.setValue: Set the value of an input field.

javascript
Copy code
browser.setValue('#selector', 'value');

• browser.clearValue: Clear the value of an input field.

javascript
Copy code
browser.clearValue('#selector');

• browser.submitForm: Submit a form.

javascript
Copy code
browser.submitForm('#selector');

• browser.moveToElement: Move the mouse to an element.


javascript
Copy code
browser.moveToElement('#selector', xoffset, yoffset);

• browser.dragAndDrop: Drag an element to another element.

javascript
Copy code
browser.dragAndDrop('#source', '#destination');

• browser.execute: Execute custom JavaScript on the page.

javascript
Copy code
browser.execute(function() {
// custom JavaScript
});

Assertions

• browser.assert.elementPresent: Check if an element is present.

javascript
Copy code
browser.assert.elementPresent('#selector');

• browser.assert.elementNotPresent: Check if an element is not present.

javascript
Copy code
browser.assert.elementNotPresent('#selector');

• browser.assert.visible: Check if an element is visible.

javascript
Copy code
browser.assert.visible('#selector');

• browser.assert.notVisible: Check if an element is not visible.

javascript
Copy code
browser.assert.notVisible('#selector');

• browser.assert.containsText: Check if an element contains specific text.

javascript
Copy code
browser.assert.containsText('#selector', 'text');

• browser.assert.value: Check if an input field has a specific value.


javascript
Copy code
browser.assert.value('#selector', 'value');

• browser.assert.urlContains: Check if the URL contains a specific value.

javascript
Copy code
browser.assert.urlContains('value');

• browser.assert.title: Check if the page title equals a specific value.

javascript
Copy code
browser.assert.title('title');

Elements

• browser.element: Retrieve a single element.

javascript
Copy code
browser.element('css selector', '#selector', function(result) {
console.log(result);
});

• browser.elements: Retrieve multiple elements.

javascript
Copy code
browser.elements('css selector', '.selectors', function(result) {
console.log(result);
});

• browser.getAttribute: Get the value of an attribute.

javascript
Copy code
browser.getAttribute('#selector', 'attribute', function(result) {
console.log(result.value);
});

• browser.getText: Get the text content of an element.

javascript
Copy code
browser.getText('#selector', function(result) {
console.log(result.value);
});

• browser.getValue: Get the value of a form element.


javascript
Copy code
browser.getValue('#selector', function(result) {
console.log(result.value);
});

Browser

• browser.url: Navigate to a URL.

javascript
Copy code
browser.url('http://example.com');

• browser.back: Navigate back in the browser history.

javascript
Copy code
browser.back();

• browser.forward: Navigate forward in the browser history.

javascript
Copy code
browser.forward();

• browser.refresh: Refresh the current page.

javascript
Copy code
browser.refresh();

• browser.maximizeWindow: Maximize the browser window.

javascript
Copy code
browser.maximizeWindow();

• browser.resizeWindow: Resize the browser window.

javascript
Copy code
browser.resizeWindow(width, height);

• browser.closeWindow: Close the current window.

javascript
Copy code
browser.closeWindow();

• browser.switchWindow: Switch to another window.


javascript
Copy code
browser.switchWindow(handle);

• browser.openNewWindow: Open a new browser window.

javascript
Copy code
browser.openNewWindow('tab');

In Nightwatch.js, you can retrieve an attribute or value from an element and assign it to a
variable using asynchronous commands. Here’s how you can do it:

Retrieving Attribute Example

To retrieve an attribute (e.g., href, src, data-attribute) from an element and assign it to a
variable:

javascript
Copy code
let attributeValue;

browser.getAttribute('#elementId', 'attributeName', function(result) {


attributeValue = result.value;
});

// Example usage after retrieval (make sure to handle asynchronous nature


appropriately)
console.log(attributeValue); // This might output `null` or `undefined` due
to asynchronous execution

Retrieving Text Content Example

To retrieve the text content of an element and assign it to a variable:

javascript
Copy code
let textContent;

browser.getText('#elementId', function(result) {
textContent = result.value;
});

// Example usage after retrieval (make sure to handle asynchronous nature


appropriately)
console.log(textContent); // This might output `null` or `undefined` due to
asynchronous execution
Handling Asynchronous Nature

Nightwatch.js commands are asynchronous, meaning you'll typically need to handle them using
callbacks, promises, or async/await syntax to ensure that you wait for the result before using the
assigned variable. Here’s an example using async/await:

javascript
Copy code
async function getValueAndLog() {
let attributeValue = await new Promise((resolve) => {
browser.getAttribute('#elementId', 'attributeName', function(result) {
resolve(result.value);
});
});

console.log(attributeValue);
}

getValueAndLog(); // Call the async function to execute the retrieval and


logging

Alert commands:
Dropdown commands:
IFrame notes:
Window handles:

You might also like