Thursday, March 12, 2015

Unit Testing in Javascript and Angular

Each day we develop more and more web apps where the source code is 80% JavaScript. The Server side component becomes a mere data service, usually a simple RESTful service. The amount of classes and logic in the Client side is getting larger, and more complex each time, and evidently they are more likely to fail with each update of the code.


To decrease the possibility of failures in our applications there is a paradigm called Test-driven development, based on unit tests.


I believe that, nowadays, all developers have heard something about Unit Testing (UT). If this is your first time then you could start by reading some of the following links:




It is very likely that you are among those who have used Unit Tests while developing in the server side, but I’d bet you have never used Unit Tests in the Client side of your applications, specifically in Javascript and AngularJS.


Right?


If so, don’t worry, here I'll try to introduce you to this fascinating world.


The tools for UT are widespread in the Server side, either in .Net or Java you can find solutions. IDEs like Visual Studio, Eclipse and others, integrate perfectly with the Unit Testing tools and facilitate the creation and execution of Unit Tests.


But what’s happening on the other side of the fence?


This is a question that I‘ve been wondering for a long time. I confess I tried to read about this a couple of years ago and I finished a little bit disappointed. At least where I read, the generalized comments were about projects that have been abandoned, and I couldn’t find anything else interesting enough.


I think these projects were not receiving the required attention, perhaps for a cost problem, perhaps because almost everybody was doing well without using Unit Testing on Javascript, or simply perhaps because still the predominating applications had more than 70% of their source code in the Server side.


But personally, I am having a strong feeling that the development cycle is incomplete, it's like having a table with only three legs.


You can argue that so far, the table is working fine with only three legs...


And yes, it's true, but nobody will deny that supporting the table with four legs will give it more support and will make it stronger.


Observing the development of Angular during the last year I have begun to note that many of their code's examples are making use of unit testing. I went again over the subject and I'm greatly surprised.


The Unit Testing tools for Javascript and Angular have evolved very much, they are as flexible and powerful as their counterparts in the Server side. Even more, there are managers of projects and dependencies for the Client side with the same style of Maven and Gradle for the Server side.


Some of the main tools are:




However, we can create unit tests without any of the tools mentioned above. We can use one of the more evolved frameworks nowadays: Jasmine.


Jasmine is a powerful and flexible framework for unit tests in Javascript with as much or more flexibility than any of the ones that we use on the Server side. It has a very simple and intuitive syntax.


I can remember at least two or three recent projects where I’ve had to build a sort of "hand made" page to test the Angular components, either services or controllers. Well, not anymore, this is past history.


We also have the ngMock angular module that offers support for all the tasks related to unit tests on Angular's components.


There is a "seed" project in GitHub, ready to be used, including many of these tools pre-configured. In all honesty I think that, despite the facilities offered by this project, it’s too heavy and might not fit your development environment.


I actually prefer to use a pure and clean version of Jasmine. I was looking in GitHub for a cleaner boilerplate project but I haven't really found one containing exactly what I want, or maybe I got tired of looking. So, I have created a basic project containing only the required Jasmine's libraries and a couple of examples with Unit Test for Javascript and Angular. https://github.com/deisbel/angular-jasmine-standalone-seed


What are the most important elements of Jasmine that we need to use? - Only a few:


- A copy of the jasmine-standalone libraries.
This translates to just download the libraries from the Jasmine website and add them to the project's root folder.


- Create unit tests.
This is just writing tests using the Jasmine "language" and saving them in a file with extension .js. You can save these files mixed among others belonging to your app's source code or in a separate folder in the project's root folder.


- Add a simple html page in charge of running the tests, by default named SpecRunner.html.
Requesting the page from any browser is all you need to do to see the results. This page should be updated to add a reference to each test file that you have created and you want to run.


- If you also want to test components of your application defined in Angular (such as Services, Filters, and Controllers) you also must add references to angular and angular-mock libraries.


To show how simple is to write a file to create a test we will use the following Person class, serving us as target for our unit tests.




We are going to create three simple tests to verify that the Person's properties are always properly instantiated, and also, to ensure that the full name of the person is correctly created. These tests are pretty simple, but good enough for our purpose: illustrating how easy can be the process.


How should we define our SpecRunner.html file to execute all of these test?


It should look like this:




So far, I've shown you the less complex cases, only for a pure Javascript class, but how can I create unit tests for my Angular app components?


It's enough by adding a couple more references to our SpecRunner.html page, one for angular.js and another for angular-mocks.js.


Also, you can see that we added two more references, one for the file where an Angular controller is defined and another for the file where the unit tests for that controller are created. The content for each file is below:






If you refresh the SpecRunner.html page to execute again the tests you will see these results:




You can add more files containing classes and tests as you need them.


After reading this article you don’t have any more excuses to ignore unit testing in the Client side, and we can finally add the fourth leg to our table, achieving more reliable apps, happier users and clients.


To deepen in the topic I give you the main links:




To download the project and collaborations:
https://github.com/deisbel/angular-jasmine-standalone-seed




Pruebas unitarias en Javascript y AngularJS

Cada vez desarrollamos más aplicaciones web donde el 80% de la misma es código fuente Javascript. El componente del servidor se convierte en un mero servicio de dato, casi siempre un simple servicio RESTful. La cantidad de clases y lógica en el lado cliente es cada vez más grande y compleja, y evidentemente será más propensa a fallar con cada actualización que reciba la aplicación.


Para disminuir la posibilidad de fallos en nuestras aplicaciones existe un paradigma que se llama Test-driven development, basado en pruebas unitarias.


Creo que, a estas alturas, todos los desarrolladores han escuchado algo acerca de Pruebas Unitarias (Unit Test - UT). Si es su primera vez entonces deberá comenzar leyendo alguno de estos enlaces y profundizar con otros:




Es muy probable que se encuentre entre los que sí han utilizado los Test Unitarios para sus desarrollos en el lado del Servidor pero me atrevería a apostar que muy pocos lo han utilizado en el lado Cliente de las aplicaciones, específicamente en Javascript y AngularJS.


Cierto?


Si es asi no se preocupe, aquí pretendo introducirlo en este fascinante mundo.


Las herramientas para UT están muy extendidas en el lado del servidor, lo mismo en .Net como en Java, usted podrá encontrar soluciones nativas en sus herramientas de desarrollo. Los IDE como Visual Studio, Eclipse y otros, se integran perfectamente con la herramientas de UT y facilitan su creación y ejecución.


Pero, qué hay en la otra orilla?


Esta es una pregunta que hacía tiempo me venía haciendo y confieso que cuando hace un par de años leí sobre el tema resultó más en desilusión que en otra cosa. Al menos donde lei comentaban que algunos proyectos que habían comenzado ya ni siquiera se continuaban desarrollando. Creo que tampoco se le estaba dando la importancia que requería, quizás por un problema de costos, quizás porque a casi todos les iba bien sin Pruebas Unitarias en Javascript, o quizás simplemente porque aún predominaban las aplicaciones con más del 50% de su código en el lado del servidor.


Pero en lo personal, vengo teniendo la fuerte sensación que el ciclo de desarrollo esta incompleto, que tenemos una mesa de 4 patas pero la estamos sosteniendo solo con 3. Que no se ha caído? - Cierto, pero nadie negará que una de 4 tendrá más soporte.


Observando el desarrollo de Angular en el último año he comenzado a ver que en muchos de sus códigos de ejemplo hacen uso de test unitarios y esto comenzó a llamar mi atención. Mi sorpresa ha sido grande al revisar nuevamente sobre el tema.


Los herramientas de UT para Javascript y Angular están muy evolucionadas, siendo tan flexibles y poderosas como las de sus homólogas en el lado del servidor. Incluso existen ya manejadores de dependencias y proyectos al mismo estilo de Maven y Gradle para los proyectos clientes.


Entre las principales herramientas están:




No obstante todas las anteriores son herramientas de las cuales podemos prescindir. Nosotros podemos usar directamente el framework para Pruebas Unitarias que más desarrollado está, cuyo nombre es Jasmine.


Jasmine  es un poderoso y flexible framework para pruebas unitarias en Javascript con tanta o más flexibilidad que cualquiera de los que usamos en el lado del servidor. Con una sintaxis bien simple e intuitiva.


A la memoria me vienen al menos 3 o 4 proyectos recientes en los que he tenido que hacer a mano “páginas de pruebas” para el código de Angular, tanto para la capa de servicio como para los controladores. Pues bien, esto ha llegado también a su fin.


También tenemos en angular el módulo ngMock que nos ofrece soporte para todas las tareas relacionadas pruebas unitarias sobre componentes de Angular.


Existe en GitHub un proyecto “semilla”, listo para usar, incluyendo muchas de estas herramientas ya preconfiguradas. En honor a la verdad creo que a pesar de sus facilidades tiene demasiadas cosas para mi gusto que realmente no necesitamos pues muchas veces tenemos nuestros propios entornos de desarrollo.


Yo realmente prefiero usar una versión pura y limpia de Jasmine. Estuve buscando en GitHub un proyecto semilla para ello y realmente no he encontrado uno exactamente como lo quiero, o me canse de buscar quizás. Entonces he creado un ejemplo básico conteniendo solo las bibliotecas requeridas de Jasmine, versión “standalone” y un par de ejemplos con pruebas unitarias Javascript puro y Angular: https://github.com/deisbel/angular-jasmine-standalone-seed


Cuales son los elementos más importantes de Jasmine que necesitamos utilizar? - Solo unos pocos:


  • Una copia de las bibliotecas de jasmine-standalone.
    Esto se traduce en simplemente descargarlas desde su sitio web y agregarlas a la carpeta raíz de nuestro proyecto.
  • Crear los test unitarios.
    Esto no es más que sentencias de código Jasmine en archivos javascript. Puede ubicarlos mezclados dentro del codigo fuente de la aplicacion o en una carpeta por separado en la raíz del proyecto.
  • Agregar una simple página html preparada para correr las pruebas. Por defecto suele tener el nombre SpecRunner.html.
    Pedir la pagina desde un navegador es todo lo que necesitará para correr los test y ver los resultados. Esta página deberá actualizarla para agregar las referencias a los archivos de pruebas que haya creado y que desea correr.
  • Si además desea hacer test unitarios a los componentes de su aplicacion en Angular deberá agregar en la página referencias a las bibliotecas de angular y angular-mocks.


Para ilustrar cuán simple sería escribir un archivo para crear test unitarios usaremos la siguiente clase Persona, objetivo de nuestras pruebas.




Y definamos tres simples test que verifican que siempre se instancian correctamente sus propiedades y se obtenga bien el nombre completo de la Persona. Son pruebas unitarias bastante simples pero suficientes para nuestro propósito de ilustrar cuán sencillo puede ser. Para una referencia completa de lo que puede hacer con Jasmine debe remitirse a su pagina web.




Cómo debemos definir nuestro archivo SpecRunner.html para correr todas estas pruebas?


Quedaría así:




Note como existen dos secciones que deben actualizarse con cada archivo donde tenga pruebas unitarias definidas y los archivos que contengan clases que sean usadas por las pruebas unitarias. No es necesario incluir todos los archivos javascript del proyecto, solo los que nos interesan.


Una vez ejecutado en un navegador se vería así:




Hasta aquí lo más simple, solamente probando código puro de Javascript, pero, cómo lo hago si quiero hacer pruebas unitarias a un código de Angular?
- Basta con agregar un par de referencias a angular.js y angular-mocks.js en el archivo SpecRunner.html




De paso ya puede ver que agregamos un par de referencias más, una al archivo donde esta definido el Controlador que queremos probar y una al archivo donde están definidas las pruebas unitarias para este. El contenido de estos archivos es el siguiente:






Si ahora refrescamos la página SpecRunner.html para correr las pruebas nuevamente veremos estos resultados:




Puede agregar más archivos con clases y pruebas a medida que los vaya necesitando.


Espero que después de este artículo no tengamos más pretextos para no usar pruebas unitarias en lado del cliente y podamos cerrar un circulo que por momentos se resistía. Con esto lograremos hacer los módulos de clientes en Javascript más fiables y menos propensos a errores durante su desarrollo y posteriores actualizaciones.


Para profundizar en el tema le dejo los principales enlaces:




Para descargar el proyecto completo y colaborar:
https://github.com/deisbel/angular-jasmine-standalone-seed







Tuesday, March 10, 2015

Podcast #3 Una semana más tarde

Episodio 3   —  noviembre 23 de 2014


Deisbel es papá por primera vez, así que una semana más tarde de lo previsto continuamos hablando sobre optimización de sitios web.
En este episodio:


La frase del día: "Somos cubanos, y tenemos un poquito de españoles y un poquito de americanos".