Saturday, 11 October 2014

Simple UI testing with Nightwatch.js

This week I was introduced to Nightwatch.js by my colleague Matt Davey.  Nightwatch provides a clear and simple syntax for writing your UI tests and uses NodeJS and Selenium to run the tests. 

Having played with Canopy for UI testing, the high readability of the test syntax impressed me from the start.  We used it to nail down a reproduction of a bug we were working in our test environment.

Test scenario

Our test did something like this
  • Logs into a site using known credentials.
  • Clicks through to a place in the UI.
  • Changes and saves a value.
  • Asserts that the new value is being displayed in another area of the UI.

The test syntax

The test syntax looks like this:

The syntax is clean, easy to read and all in a one file. One of the CSS selectors is pretty evil, but you can get that from the browser’s context menu in the inspector (which I learnt this week too!):


Setting up the test runner

Setting up to run the test is very simple to do on any development or test machine. You the components are:
  • NodeJS
  • NPM
  • Nightwatch
  • A Selenium Server
You can install Java, NodeJS and Nightwatch using Chocolatey by opening a command window and running:

choco install javaruntime
choco install nodejs.install

npm install -g NightWatch

Note that Chocolatey seems to install the Node packages under Chocolatey's folders, and NPM then places the Nightwatch module into the nodejs.commandline folder under \tools.  In there is a batch called Nightwatch.cmd in there that we need to access. So, we need to add the following to our path:

C:\ProgramData\chocolatey\lib\ nodejs.commandline.X.Y.Z\tools

(where X.Y.Z is the NodeJS version we’ve installed.)

Then we need to start up a Selenium server.  It would be nice to use Chocolatey here too, but the version of Selenium from the package at time of writing is too old.  So, download the latest Selenium driver (JAR) from here (which is 2.43 at time of writing).

Rename the Selenium JAR file to selenium-server-standalone.jar and save it to C:\selenium\. Then start up a Selenium Server for opening a new command window (as admin) and typing:

java -jar "C:\selenium\selenium-server-standalone.jar"

That’s the setup done, now let’s run the test.

Running the test

Save your test (similar to the code above) to a file, let’s say repro.js, into a folder.  Create a sub-folder called “examples\custom-commands” (which Nightwatch wants to find, not sure why!).
Then open another command window and change to the folder containing the test file and run the following:

nightwatch --test repro.js

Job done!


pemanas air wika said...

thank you for sharing, keep posting!

Anonymous said...

idi**, add code as picture