Single page applications are significant part of a modern web. Their scale is increasing from simple tools to large webpages. Because of that, we as developers have to be sure that our apps are working as expected, and that new features we are implementing would not break other parts of our page.
According to W3Thechs, high traffic sites, such as Weather.com, Ford.com are using AngularJS library. The fast-growing popularity of AngularJS in comparison to ember.js and backbone.js is also illustrated in the graph bellow:
In this article we will discuss how to create simple but efficient workflow for writing unit tests with Grunt and AngularJS. The main tools to be used are:
NPM, Bower - package managers
The main goal of this tutorial is to run unit tests automatically during the development, and create a simple test-first workflow.
First of all, let us install few packages with NPM:
These are packages required for our local server. Another important group of packages are those, required for karma:
After installing packages in your package.json file you will find a section with devDependencies:
Although we have some packages for Grunt installed, we still need the AngularJS. Now we will install it using Bower.
After installing bower componenets, we need to create a Gruntfile.js – a file with our tasks. If you are not sure how to do this, please have a look at the documentation
Now my file looks as follows:
Please have a look on the section karma. There are two main properties which help us run tests in the background:
Also, we added karma task in watch section for each and every change of *.js files:
The above written code is the karma trigger that runs the tests.
Last but not least, we need to keep both the karma and local servers running. In order to do this, please create a new task:
In console, after entering the command grunt live, these tasks will be executed. The first one is karma:unit, which starts karma server, the second one – connect-livereload – starts local server with live reload option. The last one – watch – is listening to changes in the files.
As soon as we finish the configuration, we create a new app. What we need is app/index.html, app/scripts/app.js and app/scripts/app_tests.js. In this project they are in the app folder.
Run command grunt live to run the server and add the first test:
After saving the file in the console you will find:
The test we have written failed, but this is fine. Now, we will write code for our test. In app.js you need to add a new variable in MainController controller:
Now please save the file and have a look at the console window:
As you can see, now we have our project configured for test-first development. The whole project is available here. Please download the archive, unpack to any folder and install there the packages with commands: npm install and bower install. Now start the project with command grunt live and… have fun!