terça-feira, 18 de agosto de 2015

Bulletproof frontend tests

In the last article I have talked about how to start make a front end test with CasperJS, you can see the post here.

Now I will make some improvements in this test to make it bulletproof.

Let’s work.

The first step is wait for element be present before read any property or value, if the element is not presented a problem occurred in the page load and will break the test.

Analysing the code of the first test case it can be refactored to detect the element present before assert their values. I will create a new step in the test runner to perform this verification using the method assertExists. This method has the selector as parameter.

This code execution result will be:

Another approach is wait for some selector present in the page before start the assertions. To perform the same test case using this strategy I will use the casper method waitForSelector. The method accept four parameters: the element selector, then function, onTimeout function and timeout counter value.

All my assertions will be inside a waitForSelector then function block to avoid access to elements with no presence confirmed. In the example I choose one selector used in the assertions to wait for his presence.

This code execution result will be:

If the test fail the result will be like:

Executing all tests in the folder

I recommend you to isolate the assertions per functionality. In the example test case we have a minimalist scenario but when is increased your application more complex will be your test. Isolate the assertions from element present from the element values assertions is a good tip.

You can see this code working on my github https://github.com/ferfabricio/casperjs-test-example