Web UI Testing in NodeJS
Tags: node, mocha, casperjs, phantomjs
Published: 2018-02-28 16:37:20

---
title: Web UI Testing in NodeJS
published: true
description: A PhantomJS and CasperJS example for testing web UI.
tags: [
  NodeJS,
  Mocha,
  CasperJS,
  PhantomJS
]
---

_Originally posted on [Boatswain Blog](https://blog.boatswain.io/post/web-ui-testing-in-nodejs/)._

---

![](https://thepracticaldev.s3.amazonaws.com/i/xxoygn37j7vvt3aqijp7.png)

In this article i would like to demonstrate some tools in [NodeJS][nodejs] for testing web UI. They are:

- [Mocha][mocha]
- [Chai][chai]
- [CasperJS][casperjs]
- [PhantomJS][phantomjs]

#### Mocha

[Mocha][mocha] is a Javascript framework for testing. It has a _BDD-style_ syntax **(BDD: [Behavior-driven development][bdd])** and allows asychronous call testing. It also supports different assertion libraries and in our exampe we will use [chai][chai] for assertion.

#### Chai

[Chai][chai] is a [BDD][bdd]/[TDD][tdd] assertion library for [NodeJS][nodejs] and the browser that can be delightfully paired with any Javascript testing framework.

#### CasperJS

[CasperJS][casperjs] is a helper library for building navigation scenarios. It is often used with [PhantomJS][phantomjs] but actually it also supports [SlimerJS][slimerjs] which is another headless browser with the [Firefox][firefox] rendering engine called [Gecko][gecko].

#### PhantomJS

[PhantomJS][phantomjs] is a headless browser with the [WebKit][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][casperjs].

The second question is a bit more complicated. It could be broken down into the following steps.

1. _Wait for the search form_
1. _Fill in the form and submit_
1. _Check if the result set contains the search text_

Let's go through the code.

### Initialize a new NodeJS project

```shell
npm init
```

### Install the following node modules

```shell
npm install casperjs chai mocha phantomjs --save-dev
# In addition to the above libraries, we also need the following extensions.
npm install casper-chai mocha-casperjs --save-dev
```

### Setup the tests

Create the _test/google-search.js_

```javascript
describe('Google Search', function() {
  // Before script for each test
  before(function() {
    casper.start('https://www.google.com.hk/');
  });

  // *** Test 1 ***
  // Is the Google search page accessible?
  it('should have return HTTP 200', function() {
    expect(casper.currentHTTPStatus).to.equal(200);
  });

  // *** Test 2 ***
  // Is the search function able to return a list of result?
  it('should be able to search', function() {
    // Wait for the search form
    casper.waitForSelector('form[action="/search"]', function() {
      'form[action="/search"]'.should.be.inDOM;
    });

    // Fill in the form and submit
    casper.then(function() {
      this.fill('form[action="/search"]', { q: 'Boatswain' }, true);
    });

    // Check if the result set contains text "Boatswain"
    casper.waitForSelector('h3.r a', function() {
      'h3.r a'.should.be.inDOM;
      expect('h3.r a').to.contain.text(/Boatswain/);
    });
  });
});
```

### Add a npm script for running the test

Edit the _package.json_ as follow.

```json
{
  "name": "ui-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "mocha-casperjs test/google-search.js"
  },
  "author": "ykyuen",
  "license": "ISC",
  "devDependencies": {
    "casper-chai": "^0.3.0",
    "casperjs": "^1.1.4",
    "chai": "^4.1.2",
    "mocha": "^4.1.0",
    "mocha-casperjs": "^0.6.0",
    "phantomjs": "^2.1.7"
  }
}
```

### Run the test

```shell
npm test
```

![Test passed!](https://thepracticaldev.s3.amazonaws.com/i/f776ftbakdfvj44pvdfp.jpg)

<center>Test passed! ✅</center>

A brief test report will be shown after the test run has finished.

### Let's try to fail the test

```javascript
// Check if the result set contains text "Boatswain"
casper.waitForSelector('h3.r a', function() {
  'h3.r a'.should.be.inDOM;
  expect('h3.r a').to.contain.text(/nosuchtext/);
});
```

![Test failed!](https://thepracticaldev.s3.amazonaws.com/i/h82xqkcjhsk2touxgrna.jpg)

<center>Test failed! ❌</center>

## Summary

This example shows how to create a simple web UI test in [NodeJS][nodejs] and execute the test in command line prompt. It could be used in [smoke testing][smoke_testing] for staging environment. Please also note that [CasperJS][casperjs] is **NOT** for unit testing but rather web UI testing. In addition, test runner like [Karma][karma] does not support [CasperJS][casperjs]. If you are looking for unit testing solution, you should probably rule out [CasperJS][casperjs].

Complete example is available on [gitlab.com](https://gitlab.com/ykyuen/glide-example).





[mocha]: https://mochajs.org/
[chai]: http://chaijs.com/
[casperjs]: http://casperjs.org/
[phantomjs]: http://phantomjs.org/
[bdd]: https://en.wikipedia.org/wiki/Behavior-driven_development
[tdd]: https://en.wikipedia.org/wiki/Test-driven_development
[nodejs]: http://nodejs.org/
[slimerjs]: https://slimerjs.org/
[firefox]: https://www.mozilla.org/
[gecko]: http://geckoisgecko.org/
[webkit]: https://webkit.org/
[smoke_testing]: https://en.wikipedia.org/wiki/Smoke_testing_(software)
[karma]: https://karma-runner.github.io