segunda-feira, 17 de agosto de 2015

Testing your frontend with CasperJs

Any software delivery has a purpose to correct any bug or add a new functionality or behavior, if your purpose is delivery a bug to create new development demands is better you search a new job. A crucial point in a delivery is the validation step, there are many ways to validate if the new software deployed will not crash the system, the most used is the manual exploration.

Thinking your deliveries are manually tested you can use this steps:

  1. Run the delivery
  2. Try any flow with your user can imagine
  3. Turn off your phone and go home

I don’t believe in that, but if you can reproduce this steps without problem please let me know.

To avoid manual work in validation process you can automate some process.

I will use the CasperJS library to give some examples from how to automate test routines, I'm also assuming you have Node.js and CasperJS installed and working properly in your machine if you don’t have please look in these links how to install and configure: NodeJS, CasperJs.

Let’s walk in baby steps.

Formulating the first test case

In the first test case I need open my website and verify if the title and the primary header is correct, this test may have some criterial:

  1. Get http response code 200
  2. Title is equal to: Fernando Fabricio
  3. H1 tag is equal to: Fernando Fabricio

First step is create your test case:

CasperJS is not used for tests only, inside the casper object we have a test parameter with the instance of test executor.

You can see in action on the line 1 when we use the casper.test.begin method.

The method begin have 4 signatures, you can choose one:

  • begin(String description, Number planned, Function suite)
  • begin(String description, Function suite)
  • begin(String description, Number planned, Object config)
  • begin(String description, Object config)

In the example I use the first signature, the parameters are self described.

To run the casper tests you have to call the run() method, this method accept two parameters, the first is the onComplete function and the second is the timeout in seconds, this is the second step.

I call in the onComplete function the test.done() callback to end our test suite.

The third step is configure and start the navigation with the method start. The first parameter of this method is the URL and the second is the then() function, this function will have our assertions.

The fourth step is the assertions, the test case have three asserts to do, the http code 200, the content of title tag and the content of h1 tag.

To run the tests in the directory of the test file run this command: casperjs test yourtestfile.js

The result should be something like:

You can found this code working in my github:, for the code from this post look at v1 tag.

In the next post this test will be refactored to improve some protections to timeout and element not present.