Tag Archives: testing

A post-mortem on my first AngularJS project

Before I started my current employer down the road to AngularJS I decided to do a small (but complete) project using it just to see what it felt like. I had a colleague from my previous job who needed a website at precisely this point in time when I needed a project to do. It was small, self-contained, downloaded all of the data it needed at the time it initialized (so I wouldn’t have to start using AJAX with AngularJS and come up with a service layer when he didn’t already have one in place). In other words, it was almost like it had been designed for what I needed to learn.

It was to quote prices for custom t-shirts and it had some fairly complicated calculations it needed to do based upon shirt cost, shirt color, number of colors printed front and back, quantity of shirts, and surcharges for large shirts. Here’s the finished UI:

The interface as the user first sees it.

The interface as the user first sees it.

His original design called for buttons the user clicked to get a quote generated and to clear out a quote when the user wanted to get a new one. I wanted to see if I could use AngularJS to generate two versions of the same website using the same controller; one would have the buttons of the original design, the other would simply update all of the prices in real-time as the user selected colors, sizes, etc.

When I was done I had a couple of functions and flags the “quote button” version of the site used that the real-time update version of the page didn’t need but otherwise the same controller worked quite happily with two different versions of the UI (the original and my design). Needless to say, the real-time quote updates version of the site was much less clunky to use and is the only version of the source code I’ve made available on Github. My colleague (who also provided me with the web design) preferred it as well.

Prices and the quantity discounts update in real-time as the user changes colors, printing colors front and back, quantities, etc.

Prices and the quantity discounts update in real-time as the user changes colors, printing colors front and back, quantities, etc.

If you want to download the source code to an AngularJS app that isn’t another To-Do List or something to pull down Twitter tweets then feel free to check out this project here: https://github.com/JohnMunsch/airquotes

Now for the retrospective part of the blog. Surprisingly, there aren’t a huge number of things about the code that stand out as glaring mistakes almost five months later, despite spending hundreds of hours working with AngularJS since. Given how much I’ve learned in other parts of the framework, I think that speaks well to how much I could learn in a short time to get the project done and done fairly well. But that’s not to say that it’s perfect. Three changes I could pinpoint off the top of my head were:

  1. All of the shirt data and pricing data were just dumped as JSON into a file and used as global variables by the controller I built. Now I know that I could put them into an AngularJS service and inject them into the controller. That would be cleaner, but you won’t see it that way in the current code.
  2. I need to do another view to demonstrate how the user could flip over to a catalog of shirts in order to pick a different type of short-sleeved shirt, long-sleeved shirt, crop-top, etc. and then that would change the route to pick a different shirt. The routing for a selected shirt is in place, but the picking page isn’t. The fellow I was working with said he could provide that, but I think my example would be better if I went ahead and put one in.
  3. I do a lot of calculations and sub-calculations to bfigure the price and to figure the price at different price-break levels for the display. That code should really be unit tested. I actually did something about this recently, read on for details.

So I recently returned to the project with an eye to fixing a few things and the largest change I made was to use it to figure out how to do both unit tests and figure out how to know how much of my code was covered by the tests. The coverage report was, let’s just say highly motivating, when there were only a few tests in place so I spent a few hours writing a simple suite of tests to get me to 100% coverage.

So, if you’re interested, I can show you what was involved in getting unit tests and a coverage report added to an existing AngularJS project. First, if you haven’t already installed Node.js onto your machine, you should do so from the big green install button over here. Then run:

sudo npm install -g karma

The sudo won’t be necessary on Windows systems but on Mac OS X and Linux you’ll want it because we’re trying to install Karma, our unit test runner, globally so you can use it from any of your projects. Once you’ve done this once, you shouldn’t have to do it for each project.

npm install karma-coverage --save-dev

This gives us a Karma component which can check the percentage of our code which our tests reach. It’s uses the Istanbul project and it will show you at the line level exactly which lines are getting hit by your unit tests. The –save-dev adds it to the dev-dependencies part of your package.json file so npm knows it’s only a development dependency and not a runtime dependency.

bower install angular-mocks --save-dev

They’re different tools but both bower and npm recognize the –save-dev flag and use it the same way. In this case angular-mocks becomes a development dependency in your bower.json file. It will help us when we’re building our unit tests for AngularJS code.

karma init

The installation parts are done, now it’s time to add unit testing to a particular project. This will get Karma to ask you a series of questions and generate a configuration file. With a few tweaks to that file you’ll be ready to run unit tests and get code coverage information for your tests.

Karma init options.

Karma init options.

This screenshot shows me setting up a configuration file the same way I set up mine for this project. I picked Jasmine for writing the tests (other choices are Mocha and QUnit), I don’t use RequireJS, and you’ll notice it gave me an error message for no matching JavaScript files. That happened in this case because I was doing this test run in an empty directory, you wouldn’t see that normally.

If you actually open up the config file Karma generated at this point you’ll find it pretty easy to read. It has nice comments so you can tell where it wants you to put library files, the files you want to test, the browsers in which you want to test, etc.

You’re going to make two edits to the file at this point to get some things we want in there. This should be a one-time thing again.

There’s a files array part way down the page. Make sure you add the path to the angular-mocks.js in there.

And you’ll need to add a preprocessors section like you see below so the code coverage tool knows exactly which source it’s checking for test coverage and add ‘coverage’ to the list of reporters to turn on the coverage checker.

preprocessors: { 'app/scripts/**/*.js': 'coverage' },
reporters: ['progress', 'coverage'],

Note: If you use the latest angular-generator together with the latest Yeoman it seems like the generator now creates a Karma config file (karma.conf.js) and installs the angular-mocks so you can skip those two steps for your new project if you’re using Yeoman to generate it.

Finally there’s the writing of the tests themselves and the checking your coverage to see where else you need to craft tests.

To kick off this process, run “karma start” at the command line and Karma should now kick into gear, start up the browser or browsers you wanted your tests to run in, and start watching all of your source files for changes. This is super handy because you can save a change to a source file or a test file, Karma will notice that and rerun your tests so you get immediate feedback on whether everything is passing or not.

When I had only one test completed, this is what the coverage report looked like. Look for it in a subdirectory under the coverage directory after you've run some tests through Karma.

When I had only one test completed, this is what the coverage report looked like. Look for it in a subdirectory under the coverage directory after you’ve run some tests through Karma.

I’m not going to give instructions on writing Jasmine tests or even the specifics of writing them for AngularJS. There’s good examples for Jasmine on their website and I have to confess that most of the tests I’ve written so far focused on testing JavaScript rather than AngularJS specific items like services and directives. So I still have some learning yet to do. But for basic tests, if you look at the test/spec/airquoteSpec.js you can see 20+ tests I wrote for my code to achieve complete coverage of my main.js file.

With tests written for all the code in main.js there's lots of green and 100% coverage indicators at the top of the page.

With tests written for all the code in main.js there’s lots of green and 100% coverage indicators at the top of the page.

Good luck, I hope some of my code is helpful to you in your own projects, and feel free to ask questions about any of it.

About these ads