In this article i would like to demonstrate some tools in NodeJS for testing web UI. They are:
Mocha
Mocha is a Javascript framework for testing. It has a BDD-style syntax (BDD: Behavior-driven development) and allows asychronous call testing. It also supports different assertion libraries and in our exampe we will use chai for assertion.
Chai
Chai is a BDD/TDD assertion library for NodeJS and the browser that can be delightfully paired with any Javascript testing framework.
CasperJS
CasperJS is a helper library for building navigation scenarios. It is often used with PhantomJS but actually it also supports SlimerJS which is another headless browser with the Firefox rendering engine called Gecko.
PhantomJS
PhantomJS is a headless browser with the WebKit rendering engine. It allows running browser-based tests in a headless system.
Check if the Google search is working
Let’s get started with a simple example. Assume we would like to test the following:
- Is the Google search page accessible?
- Is the search function able to return a list of result?
For the first question, we could simple make a HTTP request to the Google URL and see if it returns a HTTP 200 response code and this could be done easily by CasperJS.
The second question is a bit more complicated. It could be broken down into the following steps.
- Wait for the search form
- Fill in the form and submit
- Check if the result set contains the search text
Let’s go through the code.
Initialize a new NodeJS project
|
|
Install the following node modules
|
|
Setup the tests
Create the test/google-search.js
|
|
Add a npm script for running the test
Edit the package.json as follow.
|
|
Run the test
|
|
A brief test report will be shown after the test run has finished.
Let’s try to fail the test
|
|
Summary
This example shows how to create a simple web UI test in NodeJS and execute the test in command line prompt. It could be used in smoke testing for staging environment. Please also note that CasperJS is NOT for unit testing but rather web UI testing. In addition, test runner like Karma does not support CasperJS. If you are looking for unit testing solution, you should probably rule out CasperJS.
Complete example is available on gitlab.com.