Test Automation using NightWatch – Part 1

Nightwatch Examples

In this blog series, I’m going to show you what I’ve learned automating using NightwatchJs.

A NightwatchJs is an E2E testing framework used for automating browser web apps. It uses the W3C WebDriver API as the underlying to perform automation.

It has the built in test runner, which can run the tests even in parallel, by group and tags. It comes with the out-of-the box solution to execute tests on cloud testing services, such as SauceLabs and BrowserStack.

By default, it provides the JUnit XML report generated after the execution which is easy to integrate with the CI tools such as Jenkins, TeamCity and so on.

What are we going to automate?

We are going to automate The Internet website. While performing automation, we together solve problems / challenges.

Let’s start!

Pre-requisites

Node with NPM (I’m using Node v7.1.0 and npm v3.10.9)

(Optional) Yarn (I’m using Yarn v0.17.6)

Chrome browser (My chrome version is 57.0)

Sample code

This is an optional step. The example that we are going to see in this article are available in the github. Follow the steps to clone and run:

We have to clear the default_path_prefix, as it is by default set to /wd/hub which chromedriver doesn’t require it.

Create a chrome driver global file

A global file is the js file which will be loaded by the test runner and made available to the test. We’ll be using this file to start the chromedriver before the test starts and quits the chromedriver after the test finishes its execution.

Each file in the tests directory is considered as test suite. Here, in the HomeTest.js we have created one test called Test Home Page. Each test function will have one parameter which holds the webdriver instance. Here, we are calling that instance as client. All the nightwatch webdriver commands are accessed through this instance.

The client.init() will launch the browser with the url configured in the launch_url property in the nightwatch.json. In our case, it will open the chrome browser and launch http://the-internet.herokuapp.com/.

Then it will wait for the body tag to be visible for maximum of 1 sec.
After that we assert the title to be equal to The Internet. Then we expect an element with class attribute .heading and with text to be equal to Welcome to the Internet.

The client.end() is mandatory to close the browser instance and stop the selenium server instance.

Here we have added another test called Navigate to Broken Images page in which we navigate to the Broken Images page and assert the heading.
Note that we have removed the client.end() from the first test and moved that to the second test.

Execute again and see both of your tests run.

Finally, we have two tests which runs successfully.

In the next part, we’ll make our tests more maintainable using page object pattern.